❔ Need help explaining precedence in C#
Why is the above code does it evaluate to 35?
Why is it not
y = 5
y += y // 10
x += y // 20
13 Replies
C# operators and expressions - List all C# operators and expression
Learn the C# operators and expressions, operator precedence, and operator associativity.
so first
x += y
(x is 30, y is 20)
then 30 is used from that expression
x += y = 5
(y is set to 5 then added to x)but isnt += and = right associative?
so why would x += y be first
"Right-associative operators are evaluated in order from right to left. The assignment operators, the null-coalescing operators, lambdas, and the conditional operator ?: are right-associative. For example, x = y = z is evaluated as x = (y = z)."
right, y += y = 5 is first
remember that
y += y = 5
becomes y = y + (y = 5)
the y
on the left of the +
is read before the assignment
so y = 20 + (y = 5)
then 25 is assigned to y, and becomes the value of the expressionnot sure i understant
y = y + (y = 5)
so y = 5 is first
so y = 5 + 5
no, y = 5 is not first
why if its right associative
+ is left associative
well, + has higher precedence than =
but
so += is right, but + is left
well, i don't think it matters in this case.
y = y + (y = 5)
can only be intrpreted one way. y = a + b
means "evaluate a, then evaluate b, then add them." in this case, a is y
and b is (y = 5)
to put it another way, the associativity only describes how to add parentheses to an expression. so, if you have a + b + c
, if you were to add parentheses that kept the expression's value the same, it would be ((a + b) + c)
, because +
is left associative
for a = b = c
, it would be (a = (b = c))
, because =
is right associative
you cannot add any more parentheses to y = y + (y = 5)
, so the associativity doesn't do anything
(well, you could do y = (y + (y = 5))
, but that happens because of operator precedence, not associativity)i think i understand more, ty
Operand evaluation order is a separate concept to precendence, see https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#1141-general In particular, look at the example.
When evaluating an expression, the operands are evaluated first, left to right. Then the operations between those operands are performed. Precedence determines the order that those operations are performed in, but it does not affect the order in which the operands are evaluated.
So, back to
x += y += y = 5;
.
We first expand the +=
(see §11.19.3):
Then we evaluate the operands:
Then we evaluate the operations between the operands, taking precedence (and the parens) into account:
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.