Why in this case a will be equal to 20, not 21?
int a = 10; a += a++; Console.WriteLine(a); This is a variation of the classical problem of ++i + ++i in a somewhat simplified version.
In C ++, this is an undefined behavior, and the result in most compilers will be 21. Quoting lurkmore:
According to C and C ++ standards, side effects (that is, increment in this case) can be applied at any convenient time for the compiler between two points of repetition. The construction i = ++ i + ++ i; the compiler has the right to understand and how
tmp=i; tmp++; i = tmp; tmp++; i += tmp;And How
tmp=i; tmp++; tmp++; i = tmp + tmp;
Due to the unpredictability of behavior, this example was often suggested to be explained at interviews :)
In C #, the result is 20, since The order of calculation is explicitly specified by the specification. In C # there are no sequence points, the compiler is not so free when optimizing expressions, so it calculates in the order it was ordered to:
+= is a compound assignment operator. It is not an independent operator (it does not allow a separate overload, etc.), but simply a shortcut for
a = a + a++; Those. he simply takes the result of calculating a (10), adds to it the result of calculating a++ (10) and adds the sum (20) back to a . In this case, the operands are calculated precisely from left to right.
The process of calculating the postfix operator a ++ is described in the C #, 7.6.9 specification Postfix increment and decrement operators, and it is as follows:
therefore
a + (a++) -> 20 (a++) + a -> 21 The value of the assignment of the increment operator is not used in any of the execution paths, something similar will tell ReSharper to such code a += a++; message:
Value assigned is not used in any execution path
You simply lose your postfix increment, since it is executed after the addition operation is performed and before assignment. Now, if you use the prefix increment, then you get 21 as a result.
int a = 10; a += ++a; Console.WriteLine(a); Since the prefix increment operation is executed before addition and assignment are performed.
In the prefix form, the increment or decrement is performed before using the value in the evaluation of the expression. In the postfix form, the increment or decrement is performed after using the value in the evaluation of the expression.
References:
a += a++; ^---------- 10 ^----- 10 ^^--- 11 ^^^--- значение 10, но a=11 ^^------- 10+10 = 20 Source: https://ru.stackoverflow.com/questions/657726/
All Articles
a += ++a;-> in this caseawill be equal to21- MihailPw