Why is exchanging XOR with whole elements a warning?

I typed the following program:

#include <stdio.h>

int main(void) {
    int a = 3;
    int b = 42;

    printf("a = %d\nb = %d\n", a, b);

    printf("Exchanging values.\n");
    a ^= b ^= a ^= b;

    printf("a = %d\nb = %d\n", a, b);

    return 0;
}

and everything is in order. When I try to compile it, I get the following:

$ gcc test.c -o test -Wall -Wextra -ansi -pedantic-errors
test.c: In function ‘main’:
test.c:11: warning: operation on ‘a’ may be undefined

This is pretty standard code, right?

Why does this cause a warning? As far as I know, bitwise XOR is implemented by default for intas long as you use the standard C implementation.

Many thanks.

+3
source share
2 answers

The variable is aused as the value of l twice in the expression.

Keep in mind that this x ^= yis actually a shortcut for x = x ^ y, which means that the first operand is read and then written.

, , .

   b ^= a ^= b;    // OK
/*    2    1    */

a , b . , a ^= b, b , a , , (r1) . b ^= r1, b ( , ), . , -, undefined. a , b , , a b . .

, :

   a ^= b ^= a ^= b;    // NOT OK
/*    3    2    1    */

a , 1 3, 1 3. a 3, 1 ?

, 1 3, . . 3 a, 1, . undefined.

+13

a ^= b ^= a ^= b; Undefined . :

a ^= b;
b ^= a;
a ^= b;
+9

Source: https://habr.com/ru/post/1795048/


All Articles