What happens to this expression? b = a + (a = a + 5)

a = 5 b = a + (a = a + 5) 

result b = 15

Why does the first "a" after this not change (a = a + 5)? But why is the second changing? What exactly is happening here in steps?

+66
c #
Jan 14 '15 at 7:30
source share
4 answers

Expressions are evaluated from left to right - always, regardless of grouping. So this is equivalent to:

 a = 5; int lhs = a; // 5 int rhs = (a = a + 5); // Increments a by 5 (ie a=10), and rhs=10 b = lhs + rhs; // 15 

So, after that, a will be 10. But this only happens after a been evaluated for the first operand of the main addition, so the result is 15, not 20.

It is very important to understand that part of the evaluation order does not coincide with priority. Consider this:

 int x = First() + Second() * Third(); 

Priority means that multiplication is applied to the results of calling Second() and Third() - but First() is still evaluated first. In other words, this statement is equivalent to:

 int lhs = First(); int rhs = Second() * Third(); int x = lhs + rhs; 

For more information, see Eric Lippert's blog post on prejudice, associativity, and ordering .

I would strongly advise against writing such code.

+161
Jan 14 '15 at 7:33
source share

Unlike C and C ++, the order of evaluation of subexpressions is on the left in C #. Therefore the expression

 j= ++i + ++i ; 

has well-defined behavior in C #, and undefined behavior in C and C ++.

In expression

 b = a + (a = a + 5) 

left a will be evaluated first, then a+5 be evaluated and assigned to a , and after adding as the evaluated subexpression b will be set to 15 .

+18
Jan 14 '15 at 12:38
source share

An expression is always evaluated from left to right and then assigned to everything on the left. how

  a = 5 b = a + (a = a + 5) \\b = 5 + (a = 5 + 5) b = 15 
+10
Jan 14 '15 at 7:42
source share

We always work from left to right, only parts of the Parens group from the sum. Just remember to always go left. I went step by step below

start with a question

a = 5

b = a + (a = a + 5)

So now change the first "a" to 5

b = 5 + (a = a + 5)

now allows you to do the amount in parens

b = 5 + (a = 5 + 5)

It gives us

b = 5 + 10 or you could say b = 5 + (a = 10)

, and the answer

b = 15

also now

a = 10

+3
Jan 20 '15 at 13:50
source share



All Articles