'How will be operands inside (a += 3, 5, a) are going to dealt or caculated in order to print the value of "a"?

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.



Solution 1:[1]

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.

Solution 2:[2]

The expression a += (a += 3, 5, a) will invoke undefined behavior.

C standard says

C11: 6.5.16 Assignment operators (p3):

[...] 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.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Ruben Helsloot