Search code examples
cundefined-behaviorsequence-pointscompound-assignment

Are there sequence points in the expression a^=b^=a^=b, or is it undefined?


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?


Solution

  • a ^= b ^= a ^= b; /*Here*/
    

    It is undefined behavior.

    You are modifying an object (a) more than once between two sequence points.

    (C99, 6.5p2) "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.

    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.