-1

Possible Duplicate:
If i == 0, why is (i += i++) == 0 in C#?

I know this is not a logic implementation and I know I should use prefix ++ but I am curious about this code:

int a = 1;
a = a++;
Console.Write(a);

I expect that the result is 2 but it is not. Why is the resut 1? After a has been equilized to a, the value of a increased. But it seems ++ operation executed in another dimension :)

Community
  • 1
  • 1
pilavust
  • 538
  • 1
  • 7
  • 20

5 Answers5

16

Putting ++ after the a tells it to return the old value, then increment. At the same time, the incrementing happens before the assignment, so you lose the old value. Here is equivalent code:

int a = 1;
int temp_old_a = a; //temp_old_a is 1
a = temp_old_a + 1; //increments a to 2, this assignment is from the ++
a = temp_old_a; //assigns the old 1 value thus overwriting, this is from your line's assignment `a =` operator
Console.Write(a); //1

So you can see how it ultimately, throws away the incremented value. If on the other hand you put the ++ before the a:

int a = 1;
a = ++a;
Console.Write(a); //2

It acts like:

int a = 1;
int temp_old_a = a;
temp_old_a = temp_old_a + 1;
a = temp_old_a; //assigns the incremented value from the ++
a = temp_old_a; //assigns again as per your original line's assignment operator `a =`
Console.Write(a); //2

In this case, it usually doesn't make sense to reassign a variable when having it incremented as part of the expression. You're almost always better off just simply incrementing it:

int a = 1;
a++; //or ++a, but I find a++ is more typical
Console.Write(a); //2

It's usually more standard to see code like that and far less confusing (as you've found out).

Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
5

a++ is a post-increment, and that's the way it works. It behaves as if incrementing the variable after returning its value. Actually it increments its value but then returns the previous value.

++a on the other hand is pre-increment, which will behave as you want.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
2

Becouse a++ is post-increment - first return value and then increase it. In this case you should use only

int a=1;
a++;
Console.Write(a);

or

int a = 1;
a = ++a;
Console.Write(a);

++a is pre-increment - first increase value and then return increased value.

Mateusz Rogulski
  • 7,357
  • 7
  • 44
  • 62
0

As a note: some languages accept the following syntax:

a = ++a

which would work as you suggested, incrementing a first, and returning it afterwards :)

0

Because the ++ operand used as postfix increments the variable only after its value has been used. If you use the ++ operand as prefix, the variable is incremented before its value is used.

For example:

Case 1: postfix usage

int a = 1;

int b;

b = a++;

Case 2: prefix usage

int a = 1;

int b;

b = ++a;

In "case 1" the b variable will be assigned with value 1 and in "case 2" with value 2.

Community
  • 1
  • 1