2

I am confused by the results of the code below. Why does 'b' retain a seemingly incorrect value when doing these operations?

        int a = 0;
        int b = 5;
        a = b++;
        b = b++;            
        Console.WriteLine("For b = b++; b=" + b.ToString()); // b should be 7 but it's 6
        a = 0;
        b = 5;
        a = b--;
        b = b--;            
        Console.WriteLine("For b = b--; b=" + b.ToString()); // b should be 3 but it's 4
        a = 0;
        b = 5;
        a = b + 1;
        b = b + 1;            
        Console.WriteLine("For b = b++; b=" + b.ToString());

Output

          b=6
          b=4
          b=6

Can anyone explain this behavior in C# and how it's working?

3

4 Answers 4

4

That's indeed the behavior of postfix operators, as detailed here.

For instance, when you write:

b = b++;

The following happens:

  1. The current value of b is saved,
  2. b is incremented,
  3. The saved value of b is produced by the postfix ++ operator,
  4. The value produced by the operator is assigned to b.

Therefore, b will indeed be assigned its original value, and the incremented value is lost.

1

Because the ++ and -- operators when placed after the value will evaluate to the value itself, and then increment/decrement the value after the evaluation.

So:

int a = 0;
int b = a++;

After running this code, b will equal 0 and a will equal 1.

This is as opposed to using the operators as prefixes:

int a = 0;
int b = ++a;

After running this code, b will equal 1 and a will equal 1.

This is documented behavior and has been around for a long time.

0

The instruction a=b++ is stored on the stack but not evaluated because it was not used after that.

To get the correct result, make that instruction have a sense fro example change that line:

Console.WriteLine("For b = b++; b=" + b.ToString());

by that one:

Console.WriteLine("For a = b++; a=" + a.ToString());
Console.WriteLine("For b = b++; b=" + b.ToString()); //should give 7
1
  • are you sure it will give the value of b to 7. If i use 'a' as shown above ?
    – Abin
    Oct 28, 2013 at 12:40
0

When you use

int a = 0;
int b = 5;
a = b++;
b = b++;

You set a to be 6, and after that you set b to be 6. When you write b to commandline, it presents 6 because a was never used when incrementing b. If you want to use a as well, you'd have to make

int a = 1;
int b = 5;
b = b++;
b += a;
Console.WriteLine("For b = a + b++; b=" + b.ToString());

But overall I don't see any use in this kind of incrementation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.