Why is the value of int d 25 and not 26 after executing the following code snippet?
int n = 20;
int d = n++ + 5;
Console.WriteLine(d);
Why is the value of int d 25 and not 26 after executing the following code snippet?
int n = 20;
int d = n++ + 5;
Console.WriteLine(d);
n++ is the "post-increment operator", which only increments the value after its initial value has been used in the surrounding expression.
Your code is equivalent to:
int d = n + 5;
n = n + 1;
To increment the value before its value gets used, use ++n, the pre-increment operator.
Because you need to use ++n to use the incremented value in that expression.
See, in the expression tree it's not incrementing n and then using that value in the addition because n++ returns the value of n but increments it for the next expression used.
However, ++n will actually return the incremented value of n for this expression.
Therefore, n++ + 5 yields 25 whereas ++n + 5 yields 26.
n++ means execute the adition after the operation, so first d will equal to n+5 and then n will get raised.
Because n++ will first assign the value and after the completion of iteration it will increment thats the reason its giving 25
Hence,
int d= n++ + 5;
is interpreted as
int d = n + 5;
Because of you are using Postfix express
int d = n++ + 5;
where compiler first assign value to d, but in following
int d = ++n + 5;
You will got d's value 26
++:post increment operator.
The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented
Hence,
int d= n++ + 5;
is interpreted as
int d = n + 5;
after execution of the above interpretaion. n is incremented by 1.