'Is `x^=y^=x^=y;` correct for swapping integers in C/C++?
x^=y^=x^=y;
is a tricky/amusing implementation of the XOR swap algorithm in C and C++. It parses as x^=(y^=(x^=y));
and uses the fact that assignment operators return the assigned value. But is it correct? The GCC 10.3.0 C compiler gives me the warning operation on ‘x’ may be undefined [-Wsequence-point]
and clang 12.0.0 warning: unsequenced modification and access to 'x' [-Wunsequenced]
. Compiling as C++, clang continues to warn the same way, and GCC stops. So is this code correct in either language? It looks rather sequenced to me, but maybe it's illegal to modify a variable two times in the same statement?
As pointed out in this answer, clang++ -std=c++17
does not give the warning. With -std=c++11
the situation is as described above. So maybe my question should be further broken down into C/C++11/C++17.
Solution 1:[1]
Add --std=c++17
to your compiler and you will not get warning anymore.
There is a part that is added to C++17 that prevents undefined behavior and you need that part for it:
In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1
Though, I suggest that you never use it in your code too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Afshin |