a=b+(b=a)*0;
This sentence can swap the value between a and b.
I’ve tried it with C# and it works.
But I just don’t konw how it works.
e.g.
a = 1, b = 2
I list the steps of it as below:
b = a -> a = 1, b = 1
b * 0 -> a = 1, b = 1
b + 0 -> a = 1, b = 1
a = b -> a = 1, b = 1 ?
But the value of b may be wrong.
Could anyone help me? It puzzles me a lot.
That
(b=a)in the middle is an assignment statement settingbto the current value ofawith the side effect that its result is (the final value of)b. When that’s multiplied by 0, you get 0, but the assignment has still happened.The outer bit sets
atobplus the result of(b=a)*0(which is zero). Because the originalbhas already been used to start settingabefore the assignment in the(b=a)bit, the assignment has no effect ona. In other words, it’s an atomica = b; b = a;, swapping the two values.C# evaluates things in a strict left to right order (unlike C and C++) to avoid a large class of subtle bugs. Note that the compiler can evaluate them in a different order but only if it can determine that it will have no effect (that’s not the case here).
The snippet you posted works, but is also hideous and not a good idea, especially when you can just use the far more readable:
Tricks like what you see here, and the XOR swap trick, and Duff’s device have no place in decent, maintainable code. They’re usually a way for coders to show how clever they are but they usually just show how bad they are.
If you ever see something like that in production code, I don’t think any jury in the world would convict you for hunting down the perpetrator and beating them to death with the rolled up program listing.
You should write your code as if the next person that has to maintain it is a psychopath who knows where you live – in my case, you’d be half right – I have no idea where you live 🙂