To swap to integers, A and B, this seems to work in C,
A = A + B - ( B = A);
Why does this work? And if this works in all conditions, can this be used to shorten any other commonly implemented algorithms?
To swap to integers, A and B, this seems to work in C,
A = A + B - ( B = A);
Why does this work? And if this works in all conditions, can this be used to shorten any other commonly implemented algorithms?
Actually it invokes undefined behaviour according to standards-
C99 §6.5: “2. Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.”
You should not rely on code like that to work because it relies on the fact that it is processed from left to right.
Any implementation that does not do it like that is going to make it fail.
You should avoid writing code that does not work in all cases on all platforms and is not compiler independent, or relies on things that are not documented nor well defined.
So why does it work if you go from left to right :
Suppose A = 1 and B = 3
A = A + B - ( B = A);
A = 1 + 3 - (1) = 3
The assignment of B happens where i left the ()
Bottom line is that only when processing left to right , the assignment of B to A is happening later.
When processing right to left same example :
A = A + B - ( B = A);
A = 1 + 1 - (1) = 1
Now the assignment of B is happening first.
Again, you should not rely on code that is not clear for the reader what is happening, and which is compiler dependent which this is the case here.
This is only "shorter" than the standard/obvious way to do it, in the number of lines/semicolons used.
You should never use it.