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!