简体   繁体   中英

Java inline int swap. Why does this only work in Java

I was asked to write a swap without using temp variables or using xor and i came up with this.
In Java, this works, but in C/C++ this does not work.

I was under the impression that this would always work since the value of 'a' on the left side of the '|' would be stored in a register and then the assignment to 'a' would occur negating the effect on the assigned value for 'b'.

int a = 5;
int b = -13;
b = a | (0 & (a = b));

You are modifying a variable and reading its value without an intervening sequence point.

b =         a          + 0 *   (a = b);
//  reading a's value        modifying a

This is undefined behavior. You have no right to any expectations on what the code will do.

The C/C++ compiler optimizes the expression 0 * (a = b) to simply 0 which turns your code fragment into:

int a = 5;
int b = -13;
b = a;

In C/C++, assigment are performed in the order of expression. In Java, assignments occur last regardless of other expressions.

eg This increments in C but does nothing in Java.

a = a++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM