简体   繁体   中英

strange behavior of integers

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.

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. ie:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM