will right hand side of an expression always evaluated first

纵饮孤独 提交于 2019-12-21 20:56:42

问题


Will right side always evaluated to ahead of left side? And then the result of right side will be passed on to left side. I am not talking about the exception such as A[i]=i++

I am talking about the normal cases:

A[i] = (j+32+43 & K); 
A[j] != (A[j] + A[k]); 

will the right part of all these expression evaluated first and then the result is compared to the left side? (Always)


回答1:


In general the order of evaluation of sub-expressions is unspecified, there are a few exceptions such as logical and, logical or, comma operator, etc...

Since you comment stated you are interested in the general rule:

any operstor @YuHao if there is any general rule

that would be covered by the draft C99 standard section 6.5 Expressions paragraph 3 which says (emphasis mine going forward):

The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

this is basically the same in the draft C11 standard expect C11 does not list the exceptions so quoting C99 is more convenient. Paragraph 3 in C11 says:

The grouping of operators and operands is indicated by the syntax.85) Except as specified later, side effects and value computations of subexpressions are unsequenced.86)

Specifically for assignment operators C99 says:

The order of evaluation of the operands is unspecified [...]

and C11 says:

[...] The evaluations of the operands are unsequenced.




回答2:


No, there is no such guarantee, N1570 §6.5.16/p3 (emphasis mine):

An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment,111) but is not an lvalue. The type of an assignment expression is the type the left operand would have after lvalue conversion. 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.

Note that assignment operator "consumes" two operands and has side-effect of modifying a lvalue.




回答3:


I just encountered this today, and spent 1 hour debugging code like this:

int a[1], b=0;

a[b++] = b;

I expected a[0] to contain 0 after this, but the compiler actually decided to evaluate b++ first, then right side of assignment, and store result in a[0] (so b++ on the left side worked as it should). So this effectively became:

b++;
a[0] = b; // 1



回答4:


This will depend on the precedence and associativity of the operators involved.

A full list can be found here



来源:https://stackoverflow.com/questions/26351162/will-right-hand-side-of-an-expression-always-evaluated-first

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