1

Why Does x = ++x + x++ Give Me the Wrong Answer?

 2 years ago
source link: https://www.codeproject.com/Articles/1208666/Why-Does-x-equals-plusplusx-plus-xplusplus-Give-Me
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Pre- and post- fix increment and decrement operations are pretty easy in theory, it's only when people get creative that you get problems in practice. Basically, a prefix (++i or --i) says to increase or decrease the value before you use the variable, so the variable has the new value immediately:

Copy Code
i = 10;
x = ++i + 5;

Can be read as:

Copy Code
i = 10;
i = i + 1;
x = i + 5;

and similarly for the -- version:

Copy Code
i = 10;
x = --i + 5;

Can be read as:

Copy Code
i = 10;
i = i - 1;
x = i + 5;

The postfix version (i++ or i--) does the same thing, but after the variable has been used:

Copy Code
i = 10;
x = i++ + 5;

Can be read as:

Copy Code
i = 10;
x = i + 5;
i = i + 1;

And similarly:

Copy Code
i = 10;
x = i-- + 5;

Can be read as:

Copy Code
i = 10;
x = i + 5;
i = i - 1;

Is that it? It's a bit...simple... Yes, it is. Or, perhaps not. It is simple, if you use it in simple ways - as an array indexer for example:

Copy Code
x = myArray[index++];

Or as a loop increment:

Copy Code
for (i = 0; i < 10; i++)
   {
   WriteLine(myArray[i]);
   }

But after that, you are into a world of confusion and pain! For example, what does this leave as a value of i:

Copy Code
int i,j;

i = 10;
for (j = 0; j < 5; j++)
    {
    i = i++;
    }

The answer is: unchanged. i remains at 10. Why? Think of it like this: what does this look like if we expand it?

Copy Code
int i = 10;
i = i++;

If we write this in C#, then the IL looks like this:

Copy Code
.line 14,14 : 13,24 ''
IL_0001:  ldc.i4.s   10            Push a constant value '10' to the stack, 4 byte integer, 
IL_0003:  stloc.0                  Pop the top of the stack into local number 0
.line 15,15 : 13,21 ''
IL_0004:  ldloc.0                  Push local number 0 to the stack 
IL_0005:  dup                      Duplicate the top of the stack
IL_0006:  ldc.i4.1                 Push a constant value '1', 4 byte integer
IL_0007:  add                      Pop the top two stack items, add them, and push the result
IL_0008:  stloc.0                  Store the top of the stack in local number 0
IL_0009:  stloc.0                  Store the top of the stack in local number 0

What? In expanded C# code, that comes back as:

Copy Code
int i = 10;
int j = i;
int k = j;
k = k + 1;
i = k;
i = j;

Which is rather strange... because you could throw away the three lines in the middle without affecting the results. It shouldn't do that, should it? Yes. Yes, it should: i++ is a postfix operation: It says, "remember the value of i, then increment i by one, and then return the value you remembered". So what you have told the compiler to do is ignore the result of the increment by overwriting it with the value you started off with. Interestingly, if you try it in the Visual Studio C++ compiler...it doesn't... because it handles it differently! So, now we have the first reason why you have to be careful when you start using increment and decrement operators for real: it's effectively a side effect, a whole line of code inserted into your line, and if you don't think very carefully, it won't do what you think.

Copy Code
int i1 = i; i1 = i1 + 1; i = i

The trouble comes when you start mixing operations on the same line:

Copy Code
i = 10; x = ++i + i++;

The problem is that the language specification does not define exactly when pre- and post- fix operations should occur, or even which order the operators are evaluated, given the operator precedence rules.

Precedence and Order of Evaluation[^] says:

MSDN wrote:

Only the sequential-evaluation (,), logical-AND (&&), logical-OR (||), conditional-expression (? :), and function-call operators constitute sequence points and therefore guarantee a particular order of evaluation for their operands.

So the compiler writer is at liberty to evaluate this expession:

Copy Code
a = b * c + d * e; 

by working out b * c first, then d * e, or d * e first then b * c because it has no effect on the result of the calculation. Unless you start playing with pre and post increment operators of course - then the results change.

Which means that it's implementation specific exactly what you get as a result: The value of i should always be the same: 12 but the value of x can be different depending on the compiler (and to an extent on the target processor - ARM for example has built in pre- and post- fix increment and decrement to its "machine code" LOAD operations, so it would be quite likely that an efficient compiler would use them directly) should it be executed as:

Copy Code
i = 10; 
i = i + 1; 
x = i + i; 
i = i + 1; 

Which gives the result 22 or as:

Copy Code
i = 10; 
i1 = i; 
i = i + 1; 
x = i1 + i; 
i = i + 1;

Which gives 21 Or as:

Copy Code
i = 10; 
i1 = i; 
i = i + 1; 
x = i + i1; 
i = i + 1;

which also gives 21 by a different route. And bear in mind that the compiler does not have to evaluate the two operands of "+" in left to right order, so it could even give some very strange and unexpected results! Like 23...

Worse: the evaluation order could change between compiler versions (because it's not defined) or even as a result of optimizations: so what works in debug fails in release!

So avoid combining them: use them for "simple expressions" such as incrementing an array index each time round a loop, but don't get fancy, or your code may well fail in interesting ways...

Points of Interest

This was written originally as the answer to a question - but I could never find it when I needed it, and felt it needed to be preserved for posterity. Hence it was updated a bit, expanded, published as an article and gets higher visibility.

History

  • 1st September, 2016: Original version

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK