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 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.
As we know that comma has lowest precedence as operator so in, a + = (a + = 3, 5, a) in this what will happen is first evaluation will be like this a+3 = 4 but then it will be discarded now evalutation will be a+5 = 6 now in third step we have to do a+a right so here answer will be value from previous operation i.e. 6 and then 6+1 = 7 now we will come out of the brackets and we will do a = a+ 7 which is a = 1 + 7 so answer will be 8 so therefore (a += 3,5,a) will get you 7 and a = a + 7 will get you 8 which will be printed finally