2 ms·
a = 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 an
by ctdonath 14y ago
a = 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...