Is this a way to exchange variable values ​​with undefined behavior?

http://codepad.org/3IFTpgwR

#include <stdio.h> int main(void) { int x = 10, y = 20; x ^= y ^= x ^= y; printf("%d %d", x, y); return 0; } 

There is a double assignment to the variable x - is it incorrect?

PS: The question arose due to the fact that other languages ​​otherwise calculate this construction.

  • 2
    See my question in English SO - αλεχολυτ

1 answer 1

Yes it is. The xor-c-assignment operation (^ =) is not a sequence point .

Multiple assignment within one point of the sequence - UB.

For exchanging variables in c ++ there is std::swap()

  • And if this is written in three separate instructions? If I understood correctly, the question was about the method itself (exchange through xor), and not about how the concrete construct x ^ = y ^ = x ^ = y will be calculated; Yes, and here I have certain doubts about intolerance - after all ^ = is right associative, i.e. according to the standard, this calculation is unequivocal ... - Harry
  • точка следования outdated name. - αλεχολυτ
  • @alexolut, but what's new then? - gbg
  • one
    @gbg sequenced before (1.9 / 13) - αλεχολυτ
  • one
    The @gbg is simply in c++11 that the term sequence point no longer exists in the Standard. - αλεχολυτ