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

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-03 17:24:16

问题


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.


回答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.




回答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.



来源:https://stackoverflow.com/questions/30627110/how-will-be-operands-inside-a-3-5-a-are-going-to-dealt-or-caculated-in-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!