Why is this statement not working in java x ^= y ^= x ^= y;

后端 未结 2 573
死守一世寂寞
死守一世寂寞 2020-11-30 09:21
int x=1;
int y=2;
x ^= y ^= x ^= y;

I am expecting the values to be swapped.But it gives x=0 and y=1. when i tried in C language it gives the corre

2条回答
  •  旧巷少年郎
    2020-11-30 09:43

    Mark is completely correct about how it evaluates in Java. The reason is JLS §15.7.2., Evaluate Operands before Operation, and §15.7, which requires evaluation left to right:

    It is equivalent (by §15.26.2, Compound Assignment Operators) to:

    x = x ^ (y = y ^ (x = (x ^ y)));
    

    We evaluate left to right, doing both operands before the operation.

    x = 1 ^ (y = y ^ (x = (x ^ y))); // left of outer 
    x = 1 ^ (y = 2 ^ (x = (x ^ y))); // left of middle 
    x = 1 ^ (y = 2 ^ (x = (1 ^ y))); // left of inner
    x = 1 ^ (y = 2 ^ (x = (1 ^ 2))); // right of inner
    x = 1 ^ (y = 2 ^ (x = 3)); // inner xor (right inner assign)
    x = 1 ^ (y = 2 ^ 3); // inner assign (right middle xor)
    x = 1 ^ (y = 1); // middle xor (right middle assign)
    x = 1 ^ 1; // middle assign (right outer xor)
    x = 0; // outer xor (right outer assign)
    

    Note that it is undefined behavior in C, because you're modifying the same variable twice between sequence points.

提交回复
热议问题