Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.79/5 (63 votes)
11 Nov 2021CPOL4 min read 94.1K   20   63
When they first meet them, developers are often tempted to play with pre- and post- increment operators. Then they get confused, because they don't do what is expected. Or ... do they?

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:

C#
i = 10;
x = ++i + 5;

Can be read as:

C#
i = 10;
i = i + 1;
x = i + 5;

and similarly for the -- version:

C#
i = 10;
x = --i + 5;

Can be read as:

C#
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:

C#
i = 10;
x = i++ + 5;

Can be read as:

C#
i = 10;
x = i + 5;
i = i + 1;

And similarly:

C#
i = 10;
x = i-- + 5;

Can be read as:

C#
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:

C#
x = myArray[index++];

Or as a loop increment:

C#
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:

C#
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?

C#
int i = 10;
i = i++;

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

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

C#
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.

C#
int i1 = i; i1 = i1 + 1; i = i

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

C#
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:

C#
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:

C#
i = 10; 
i = i + 1; 
x = i + i; 
i = i + 1; 

Which gives the result 22 or as:

C#
i = 10; 
i1 = i; 
i = i + 1; 
x = i1 + i; 
i = i + 1;

Which gives 21 Or as:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

Comments and Discussions

 
GeneralMy vote of 1 Pin
tbayart2-Oct-17 22:09
professionaltbayart2-Oct-17 22:09 
GeneralRe: My vote of 1 PinPopular
Nelek3-Oct-17 11:02
protectorNelek3-Oct-17 11:02 
GeneralRe: My vote of 1 Pin
Richard MacCutchan3-Oct-17 22:01
mveRichard MacCutchan3-Oct-17 22:01 
AnswerRe: My vote of 1 Pin
Michael Haephrati4-Oct-17 2:25
professionalMichael Haephrati4-Oct-17 2:25 
QuestionIn C and C++ there's an issue Pin
irneb2-Oct-17 21:35
irneb2-Oct-17 21:35 
AnswerRe: In C and C++ there's an issue Pin
Nelek3-Oct-17 11:12
protectorNelek3-Oct-17 11:12 
GeneralRe: In C and C++ there's an issue Pin
irneb3-Oct-17 22:36
irneb3-Oct-17 22:36 
AnswerRe: In C and C++ there's an issue Pin
Bob100020-Nov-17 9:48
professionalBob100020-Nov-17 9:48 
'though strictly speaking they should just fail to compile (well if they're trying to be decent).
Perhaps the compilers should be modified to issue a job termination notice to the programmer!
GeneralRe: In C and C++ there's an issue Pin
irneb28-Jan-18 23:56
irneb28-Jan-18 23:56 
GeneralRe: In C and C++ there's an issue Pin
Bob100029-Jan-18 1:05
professionalBob100029-Jan-18 1:05 
QuestionRE: Pin
swampwiz2-Oct-17 10:09
swampwiz2-Oct-17 10:09 
AnswerRe: RE: Pin
Richard MacCutchan2-Oct-17 21:43
mveRichard MacCutchan2-Oct-17 21:43 
AnswerRe: RE: Pin
Ole Morten Heien20-Nov-17 2:49
Ole Morten Heien20-Nov-17 2:49 
Questionorder of operations Pin
avisal2-Oct-17 9:15
professionalavisal2-Oct-17 9:15 
GeneralC# section is excellent one to me Pin
Southmountain2-Oct-17 5:36
Southmountain2-Oct-17 5:36 
QuestionUB Pin
YvesDaoust2-Oct-17 3:08
YvesDaoust2-Oct-17 3:08 
AnswerRe: UB Pin
irneb2-Oct-17 21:45
irneb2-Oct-17 21:45 
PraiseFantastic answer Pin
Graham Coulby1-Oct-17 22:30
Graham Coulby1-Oct-17 22:30 
GeneralRe: Fantastic answer Pin
irneb2-Oct-17 21:40
irneb2-Oct-17 21:40 
GeneralRe: Fantastic answer Pin
dmjm-h20-Nov-17 9:56
dmjm-h20-Nov-17 9:56 
Questiongo back to schol Pin
mag131-Oct-17 11:52
mag131-Oct-17 11:52 
AnswerRe: go back to schol Pin
Richard MacCutchan2-Oct-17 0:41
mveRichard MacCutchan2-Oct-17 0:41 
GeneralRe: go back to schol Pin
mag132-Oct-17 10:45
mag132-Oct-17 10:45 
GeneralRe: go back to schol Pin
Rick York2-Oct-17 11:03
mveRick York2-Oct-17 11:03 
GeneralRe: go back to schol Pin
mag132-Oct-17 11:09
mag132-Oct-17 11:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.