The code snippet is:
int main()
{
int a = 1, b = 2, c = 3;
printf("%d", a += (a += 3, 5, a));
}
Though it displays 8 in the terminal as an output. But am not getting the concept behind it.
The expression a += (a += 3, 5, a)
will invoke undefined behavior.
C standard says
[...] The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.
It is not guaranteed that whether the left most a
will be evaluated before or after the evaluation of (a += 3, 5, a)
. That will result in undefined behavior.
This is an effect how the comma operator works, the last element is the one that is used as the value of the statement. So essentially what you got here is the following:
a += (a += 3, 5, a)
This evaluates a+=3
first, this makes a=4
this result is discarded, then evaluate 5
then this result is discarded, then evaluate a
and keep this as it's the last item. The result from (a += 3, 5, a)
is the last item which is a which is 4.
Then you get
a += 4
so a
is 8
.
Important Note: that this is an artifact of how your compiler has generated the code. The C standard doesn't guarantee the order of execution for the assignment to a
in this situation. See haccks answer for more information about that.
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