3 ms·
My solution ended up like this: a = b + (b = a) - a;
by pgsandstrom 14y ago
My solution ended up like this:
a = b + (b = a) - a;
- adlpz 14y agoOh god
- dbush 14y agoIn Java, it seems to work, but in C (gcc 4.6.3) it doesn't. a ends up unchanged, since the first instance of b contains the original value of a when evaluated. Not sure why Java evaluates it the way it does.
- emn13 14y agoThat's because java is much stricter about enforcing the order of evaluation in these kinds of aliased statements, whereas in C it's undefined and the compiler just "does something". Of course, you'd have to be a real code-masochist to do this to yourself even in java...
- ctdonath 14y agoa = b - a + (b = a); works in C. Trick is operator associativity, with the "-" left of the "+" causing the "b-a" to evaluate (and thus, cheating, causing an anonymous variable/register to store an intermediate value) before evaluating the "+" which invokes assignment of the value of a to b, then undoing the subtraction of a from b. (Yikes, did I just write that?)
- emn13 14y agoI'm almost sure this is undefined behavior! It may break on you at unexpected moments (such as when you change optimization options or compilers). I'm certain it was undefined, but perhaps some new standard is stricter (I don't think so, however). See http://en.wikipedia.org/wiki/Sequence_point http://en.wikipedia.org/wiki/Sequence_point In essence there's no guarantee the read from the first reference to b will occur before the write to the second reference. Edit: a quick skim of C++11 changes doesn't seem like it includes any changes here, just some rewording and clarification: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2239.html http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n223...