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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With