简体   繁体   中英

will right hand side of an expression always evaluated first

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)

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.

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.

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

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

A full list can be found here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM