Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

java - Operator Precedence and associativity

When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. I want to know how the following works:

i=b + b + ++b

i here is 4 So ++b didn't change the first 2 b values, but it executed first, because the execution is from left to right.

Here, however:

int b=1;
i= b+ ++b + ++b ;

i is 6

According to associativity, we should execute the 3rd b so it should be: 1+ (++1) + ( ++1 should be done first). so it becomes: 1 + ++1 + 2 =5 However, this is not right, so how does this work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are confusing precedence with order of execution.

Example:

a[b] += b += c * d + e * f * g

Precedence rules state that * comes before + comes before +=. Associativity rules (which are part of precedence rules) state that * is left-associative and += is right-associative.

Precedence/associativity rules basically define the application of implicit parenthesis, converting the above expression into:

a[b] += ( b += ( (c * d) + ((e * f) * g) ) )

However, this expression is still evaluated left-to-right.

This means that the index value of b in the expression a[b] will use the value of b from before the b += ... is executed.

For a more complicated example, mixing ++ and += operators, see the question Incrementor logic, and the detailed answer of how it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...