Multiple assignment on one line not working as expected

后端 未结 3 1601

I\'m trying to swap two ints - x and y in the example, and do it in one line without a library function.

So I started with thi

3条回答
  •  一向
    一向 (楼主)
    2021-01-17 08:43

    Lets divide and compute.

    The innermost parenthesis executes first and after all the parenthesis resolved, then the expression executes from left to right.

    x ^= (y ^= (x ^= y));   // initial statement
    
    x = x^(y = y^ (x = x^y)); //equals to 
    
    () have the highest precedence
    
    x = x^(y = y^ (x = 3^4)); // first highest precedence () 
    
    x = x^(y = y ^ (x = 7)); // still the first x is 3
    
    x = 4 ^(y = 3 ^ (x = 7));  // now 3 ^ 7 =4
    
    x = 4 ^ 4;  // now  3 ^ 7 =4
    
    x= 0;
    

提交回复
热议问题