Sagar Upadhyay
Sagar Upadhyay

Reputation: 819

Showing different output from my acceptation

Hay I didn't know even If this question has asked before but my problem is as following.
In my c# console application I had declared a variable i with assigning a value as int i = 0 and now I want increment i by 2, obviously I can use following cede.

int i = o;
i += 2;
Console.WriteLine(i); 
Console.ReadLine(); 
//OUTPUT WILL BE 2

but this one is my alternate solution. As my lazy behavior I refuse to use this code and I had used following code.

int i = 0;
i += i++;
Console.WriteLine(i);
Console.ReadLine();

In above code I had accepted FIRST i++ will increment by one and than after it will again increment by i+=i but this thing is not happen.!!!
I doesn't know why this thing is happening may be I had done something wrong or some compilation problem.????? Can any one suggest me why this happening???? I just want to know why code no 2 is not working? what is happening in there?

Upvotes: 0

Views: 70

Answers (3)

TrizZz
TrizZz

Reputation: 1200

What your code is doing:

  • "i++" is evaluated. The value of "i++" is the value of i before the increment happens.
  • As part of the evaluation of "i++", i is incremented by one. Now i has the value of 1;
  • The assignment is executed. i is assigned the value of "i++", which is the value of i before the increment - that is, 0.

That is, "i = i++" roughly translates to

int oldValue = i; 
i = i + 1 
//is the same thing as 
i = oldValue; 

The post-increment operator increments the value of your integer "i" after the execution of your i++

For your information:

 i++ will increment the value of i, but return the pre-incremented value.
 ++i will increment the value of i, and then return the incremented value.

so the best way of doing the 2 step increment is like that:

i +=2 

Upvotes: 0

Sandeep Bansal
Sandeep Bansal

Reputation: 6394

i needs to start off with 1 to make this work.

int i = 1;

EDIT::

int i = 0;
i += i++;

Your code above expresses the following:

i + 0 then add one

if you use i += ++i; then you'll get i + 1 as it processed the increment beforehand.

Upvotes: 0

Tomas Grosup
Tomas Grosup

Reputation: 6514

The i++ returns the value of i (0) and then adds 1. i++ is called post-increment.

What you are after is ++i, which will first increase by one and then return the increased number.

(see http://msdn.microsoft.com/en-us/library/aa691363(v=vs.71).aspx for details about increment operators)

Upvotes: 2

Related Questions