1

I have the following code

 int a = 1, n = 1;

Convert.ToInt32(a = a++ + n--);

Console.WriteLine("a: " + a + " n : " + n);

//If you debug the second line of the code in quick watch the answer is 3.

The answer to above code should be 2, so it is. But if i debug it and see the value in quickwatch the value of a is printed 3. Any idea why the same code results two different values.

John Saunders
  • 160,644
  • 26
  • 247
  • 397

1 Answers1

0

Also note that the increment/decrement operators tailing the variables will be executed after the variable is used in the calculation (but before the result is written into a).

This will be interpreted as a= 1 +1, not a = 2 + 0

Specifcally the programm flows:

Take 1 out of 'a' into calculation memory.

Increment 'a' by 1

take 1 out of 'n' into calculation memory

Decrement 'n' by 1

Set 'a' to the sum of the two values you extracted earlier (not the current values of those variables) Often putting seperate steps into seperate lines can yield a lot better debugging. i.e.:

Muneeb Zulfiqar
  • 1,003
  • 2
  • 13
  • 31