Precedence and associativity of operators in C [duplicate]

微笑、不失礼 提交于 2019-12-11 06:27:01

问题


Please have a look at following code snippet:

int a = 10, b;  
b = (a) + (++a);                       //2  
printf("b = %d\n", b);  

Output:

b = 22  

In statement 2, there are 4 distinct operators. Out of which () has highest precedence. Since associativity of () operator is left to right why b = 22 and not 21 ?

$ gcc --version  
gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

回答1:


b = (a) + (++a);

This has undefined behavior.

Quoting the C99 standard (actually the N1256 draft), 6.5p2:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

This expression both reads the value of a and updates it, and the read operation (the LHS of the +) is not used to determine the value to be stored by the write operation (the RHS of the +).

The 2011 ISO C standard (quoting from the N1570 draft) states this differently, but with essentially the same meaning:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.

(a) is a value computation using the value of a; (a++) is a side effect on a. Since the order of evaluation of the operands of + is not specified, these two operations are unsequenced relative to each other.

So it's not just a matter of the order of evaluation being undefined -- the behavior is undefined, and is not limited to the possibilities of the operands of the + operator being evaluated in either of the two possible orders.

And no, the parentheses don't change this.

Section 3 of the comp.lang.c FAQ explains this well.




回答2:


The evaluation order of + is not specified.



来源:https://stackoverflow.com/questions/16530140/precedence-and-associativity-of-operators-in-c

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