Click here to Skip to main content
13,193,442 members (54,720 online)
Click here to Skip to main content
Add your own
alternative version

Stats

7.5K views
6 bookmarked
Posted 1 Oct 2017

Why does x = ++x + x++ give me the wrong answer?

, 1 Oct 2017
Rate this:
Please Sign up or sign in to vote.
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:

i = 10;
x = ++i + 5;

Can be read as:

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

and similarly for the -- version:

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

Can be read as:

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:

i = 10;
x = i++ + 5;

Can be read as:

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

And similarly

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

Can be read as:

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:

x = myArray[index++];

Or as a loop increment:

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:

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?

int i = 10;
i = i++;

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

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

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. 

int i1 = i; i1 = i1 + 1; i = i

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

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 evenwhich 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:

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 it's "machine code" LOAD operations, so it would be quite likely that an efficient compiler would use them directly) Should it be executed as:

i = 10; 
i = i + 1; 
x = i + i; 
i = i + 1; 

Which gives the result 22 or as

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

Which gives 21 Or as

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 (becasue 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 visiblity.

History

2016-09-01 Original version.

License

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

Share

About the Author

OriginalGriff
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?

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionUB Pin
Member 120616005-Oct-17 8:25
memberMember 120616005-Oct-17 8:25 
AnswerRe: UB Pin
OriginalGriff10-Oct-17 5:06
protectorOriginalGriff10-Oct-17 5:06 
GeneralRe: UB Pin
Member 1206160010-Oct-17 5:12
memberMember 1206160010-Oct-17 5:12 
Questionmy vote of 5 Pin
Michael Haephrati4-Oct-17 2:28
professionalMichael Haephrati4-Oct-17 2:28 
GeneralMy vote of 1 Pin
tbayart2-Oct-17 22:09
membertbayart2-Oct-17 22:09 
GeneralRe: My vote of 1 Pin
Nelek3-Oct-17 11:02
protectorNelek3-Oct-17 11:02 
GeneralRe: My vote of 1 Pin
Richard MacCutchan3-Oct-17 22:01
protectorRichard 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
memberirneb2-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
memberirneb3-Oct-17 22:36 
QuestionRE: Pin
swampwiz2-Oct-17 10:09
memberswampwiz2-Oct-17 10:09 
AnswerRe: RE: Pin
Richard MacCutchan2-Oct-17 21:43
protectorRichard MacCutchan2-Oct-17 21:43 
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
memberSouthmountain2-Oct-17 5:36 
QuestionUB Pin
YvesDaoust2-Oct-17 3:08
memberYvesDaoust2-Oct-17 3:08 
AnswerRe: UB Pin
irneb2-Oct-17 21:45
memberirneb2-Oct-17 21:45 
PraiseFantastic answer Pin
Apalis1-Oct-17 22:30
memberApalis1-Oct-17 22:30 
GeneralRe: Fantastic answer Pin
irneb2-Oct-17 21:40
memberirneb2-Oct-17 21:40 
Questiongo back to schol Pin
mag131-Oct-17 11:52
membermag131-Oct-17 11:52 
AnswerRe: go back to schol Pin
Richard MacCutchan2-Oct-17 0:41
protectorRichard MacCutchan2-Oct-17 0:41 
GeneralRe: go back to schol Pin
mag132-Oct-17 10:45
membermag132-Oct-17 10:45 
GeneralRe: go back to schol Pin
Rick York2-Oct-17 11:03
memberRick York2-Oct-17 11:03 
GeneralRe: go back to schol Pin
mag132-Oct-17 11:09
membermag132-Oct-17 11:09 
GeneralRe: go back to schol Pin
Richard MacCutchan2-Oct-17 21:32
protectorRichard MacCutchan2-Oct-17 21:32 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171018.2 | Last Updated 1 Oct 2017
Article Copyright 2017 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid