6

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);
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Johannes
  • 134
  • 10
  • 5
    possible duplicate of [What is the difference between ++i and i++](http://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i) – Sam Leach Oct 15 '13 at 12:18
  • See also: https://communities.coverity.com/blogs/development-testing-blog/2013/09/24/c-c-and-c – Rowland Shaw Oct 15 '13 at 12:20

6 Answers6

11

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.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
3

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.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
2

n++ means execute the adition after the operation, so first d will equal to n+5 and then n will get raised.

Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
2

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;
Neel
  • 11,625
  • 3
  • 43
  • 61
1

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

Manwal
  • 23,450
  • 12
  • 63
  • 93
1

++: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.

smRaj
  • 1,246
  • 1
  • 9
  • 13