Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 810
HBP Avatar asked Dec 12 '22 01:12

HBP


2 Answers

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.

like image 187
Benjamin Lindley Avatar answered Dec 28 '22 06:12

Benjamin Lindley


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;
like image 35
Simeon Visser Avatar answered Dec 28 '22 06:12

Simeon Visser