3 ms·
In that case, you can get the right behavior by just swapping the variables using a temporary variable. If the compiler is decent, it'll automatically swap thei
by pjscott 16y ago
In that case, you can get the right behavior by just swapping the variables using a temporary variable. If the compiler is decent, it'll automatically swap their uses later on.
I don't know how every compiler works, but if you use Clang (or anything LLVM-based), it converts everything to Single Static Assignment (SSA) form:
int x1 = 42, y1 = 666;
...
int tmp = x1; x2 = y1; y2 = tmp; // SWAP(x, y)
foo(x2, y2);
In SSA form, the value of a variable does not change, so it ends up creating a bunch of "imaginary" variables to hold intermediate values. From there, it does optimizations, then figures out how best to allocate registers, and what needs to be stack-allocated.
- leif 16y agoCool, thanks. I know far too little about compiler optimizations, it's always nice to hear about them.