The allegedly "clever" (but actually inefficient) way of swapping two integer variables, instead of using temporary storage, often involves this line:
int a = 10;
int b = 42;
a ^= b ^= a ^= b; /*Here*/
printf("a=%d, b=%d\n", a, b);
But I'm wondering, compound assignment operators like ^=
are not sequence points, are they?
Does this mean it's actually undefined behavior?
They are not.
Yes it is. Don't use this "clever" technique.
There are no sequence points in that expression, so it produces undefined behavior.
You could fix it trivially and retain most of the succinctness by using the comma operator, which does introduce sequence points:
The order of the evaluation of the
^=
operators is well defined. What is not well defined is the order in whicha
andb
are modified.is equivalent to
An operator cannot be evaluated before its arguments are evaluated, so it is definitely going to execute
a ^= b
first.The reason to have this be undefined behavior is that, to give the compiler more flexibility in doing optimizations, it is allowed to modify the variable values in any order it chooses. It could choose to do this:
or this:
or even this:
If the compiler could only choose one of those three ways to do things, this would just be "unspecified" behavior. However, the standard goes further and makes this be "undefined" behavior, which basically allows the compiler to assume that it can't even happen.
It is undefined behavior.
You are modifying an object (
a
) more than once between two sequence points.Simple assignments as well as compound assignments don't introduce a sequence point. Here there is a sequence point before the expression statement expression and after the expression statement.
Sequence points are listed in Annex C (informative) of the c99 and c11 Standard.