简体   繁体   中英

Operator precedence and Associativity in C/C++

Please note, that this has nothing to do with Operator Precedence.. () and ++ , Undefined behavior and sequence points , Why are these constructs (using ++) undefined behavior? and the hundreds similar questions about this here


Shortly : is the Associativity guaranteed by the standard?

Detailed example : from Wikipedia 's article for operator precedence, operator* and operator/ have the same priority and they are Left-to-right operators. Does this mean, that the standard guarantees , that this:

int res = x / y * z / t;

will be evaluated as

int res = ( ( x / y ) * z ) / t;

or it's implementation defined?

If it's guaranteed, could you quote?


It's just out of curiosity, I always write brackets in these cases.
Ready to delete the question, if there's such one.

From the latest publicly available draft

5.6 Multiplicative operators [expr.mul]

1 The multiplicative operators *, /, and % group left-to-right.

 multiplicative-expression: pm-expression multiplicative-expression * pm-expression multiplicative-expression / pm-expression multiplicative-expression % pm-expression 

So parsing will go like:

int res = x / y * z / t;
int res = (x / y * z) / t;
int res = ((x / y) * z) / t;

n3337 5.6/1

The multiplicative operators *, /, and % group left-to-right.

Read 5 par of standard.

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