So I came across this snippet of code in quora article to swap two numbers.
a = a + b - (b = a);
I tried this out and it worked fine. But since b = a is in parenthesis shouldn't b value be assigned the value of a first ? and the whole thing should become a + a - a making a to retain its value ?
I tried a = b + (b = a); with a = 5 b = 10 and I got a = 10 in the end. See here I guess it evaluated as a = a + a
Why this anomaly ?
This is undefined behavior because of section 6.5.2 from the C99 draft standard which states:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored
In this case we are modifying b and using it's value to determine the result of a, the standard gives the following examples as undefined:
i = ++i + 1;
a[i++] = i;
cranking up warning at least in gcc would have alerted to a problem, using -W -Wall I receive the following warning:
warning: operation on ‘b’ may be undefined [-Wsequence-point]
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