C中运算符的优先级和关联性 [英] Precedence and associativity of operators in C

查看:95
本文介绍了C中运算符的优先级和关联性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码段:

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

输出:

b = 22  

在语句2中,有4个不同的运算符.其中()具有最高优先级.由于()运算符的关联性是从左到右,为什么b = 22而不是21?

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

推荐答案

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

这具有未定义的行为.

引用C99标准(实际上是 N1256草案),6.5p2:

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.

此表达式同时读取和更新a的值,并且不使用读取操作(+的LHS)来确定要由写入操作(<<的RHS)存储的值. c5>).

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 +).

2011 ISO C标准(引用 N1570草稿)对此进行了不同的陈述,但含义基本相同:

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)是使用a的值进行的值计算; (a++)a的副作用.由于未指定+操作数的求值顺序,因此这两个操作相对于彼此未排序.

(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.

comp.lang.c常见问题解答的第3节对此进行了很好的解释.

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

这篇关于C中运算符的优先级和关联性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆