Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange answer after executing n++

Tags:

c#

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);
like image 841
Johannes Avatar asked Oct 15 '13 12:10

Johannes


1 Answers

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.

like image 180
RichieHindle Avatar answered Oct 16 '22 16:10

RichieHindle