0

I was writing very simple c++ code using pre and post increment operators, and I came across this mysterious behavior of c++ compiler. Can anyone please explain what actually happens while executing each of the print statement below....

Code

#include <iostream>

using namespace std;

int main()
{
    int i=5;
   cout <<i++<<endl;
   return 0;
}

Output of the code given above is:

5

Now I understand that since this is post increment the value of the i will be increased by 1 after the print statement!

Now lets print something different!

#include <iostream>

using namespace std;

int main()
{
    int i=5;
   cout <<i++<<i--<<endl;
   return 0;
}

Output of this program is...

45

Now I don't understand why the value of the i was decremented here even though I didn't decrement it and also I used post increment operation!

Now also if I write the same code as this...

#include <iostream>

using namespace std;

int main()
{
    int i=5;
   cout <<i++<<i<<endl;
   return 0;
}

The output of the code is

56

This output is expected and I can understand what really goes on here!

To make thing even more interesting, I eventually tried all the pre and post increment operations in single print statement, and I was just amazed by the output that I obtained!

#include <iostream>

using namespace std;

int main()
{
    int i=5;
   cout <<i++<<i--<<++i<<--i<<i<<endl;
   return 0;
}

output that I obtained was

45555

So please explain me what really happens when I print a single statement using pre and post increment operations!

And I don't understand the behavior of compiler in 2nd code segment above! Why the value of i was decremented to 4!

StackPointer
  • 529
  • 2
  • 7
  • 18
  • 1
    You are "playing" with undefined behaviour, and thus the result is up to whatever the compiler decides to do - the spec does not define which order these things should happen in. Only what the final value for ONE of the `i++` or `i--` will produce - more than one in the same "sequence point" (simply put one line of code [or more, up to a semicolon], but there are a few sequence points that aren't semicolon) – Mats Petersson Jan 25 '15 at 19:15
  • 1
    See also http://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept?rq=1 (Or one of the other 10 or so "related" links on the right of this question) – Mats Petersson Jan 25 '15 at 19:16

0 Answers0