Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 612
Devinder Kaur Avatar asked Dec 05 '22 21:12

Devinder Kaur


2 Answers

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.

like image 155
haccks Avatar answered Dec 31 '22 02:12

haccks


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.

like image 38
shuttle87 Avatar answered Dec 31 '22 02:12

shuttle87