I write this code to switch two values without temp storage and it works well, but when I try to use the same style to do other things, it doesn’t work as I expected.
`
#include <iostream>
using namespace std;
int main(){
int i=100,j=200;
//expect swich i and j
i=j+i-(j=i);
cout<<i<<" "<<j<<endl;
//expect j=100 and i=300
i=j+(j=i);
cout<<i<<" "<<j<<endl;
}
result is:
200 100
400 200
so why doesn’t the second (j=i) work?
can we just have a discussion about this situation? no one will maintain such code, including me.
This is undefined behaviour (UB). The operands to + can be evaluated in any order. The intent of your code relies on one particular order being chosen but your compiler is choosing the other evaluation order. Unlucky for you.
This experience should be enough to persuade you to avoid writing code like this. As soon as you start causing side effects in expressions you must be careful to avoid UB. Don’t be afraid of using a local temp variable when swapping. And be even less afraid of using the swap routine built into the standard library.
One final point. The fact that you don’t declare a variable does not mean that the generated code will not make use of a variable. It may be in a register, but so what, where do you think a compiler is going to put your temp int in a swap function?