简体   繁体   中英

Why does *= resolve after +

Is there ever any cuircumstance where the following algorithms are not equal?

int var1 = 2;
int var2 = 5;
int var3 = 7;

// Scenario 1
var1 *= var2 + var3; // <-- 24

// Scenario 2
var1 = 2;
var1 *= (var2 + var3); // <-- 24

The reason I ask is because msdn site states the following:

These operators have higher precedence than the next section and lower precedence than the previous section.

However, from my testing, it seems that this is never the case? And that even without the brackets, it seems to resolve as if it had brackets.

I would of thought that the algorithms would be equal to:

// Scenario 1
var1 = var1 * var2 + var3; // <-- 17

//Scenario 2
var1 = var1 * (var2 + var3); // <-- 24


So what is meant by the msdn site and in what cases is their statement true?

C# fiddle for testing:

https://dotnetfiddle.net/Yt5ZBO

So what is meant by the msdn site and in what cases is their statement true?

It means exactly what it states: the sections are ordered from higher to lower precedence.

In their list *= operator (it's a single operator and its precedence has no relations with the precedence of either = or * ) has lower precedence than the binary + operator.

So + is evaluated first.

These operators have higher precedence than the next section (+, -, *, /)

You have added the (+, -, *, /) to this quote (incorrectly), what it actually says is:

These operators have higher precedence than the next section and lower precedence than the previous section.

+ is in the previous section, so it has higher precedence.

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