Order of calculation in cascaded cout

when I run this code it gives the following output:
21 20 21

can somebody explain this output please.

#include<iostream>

using namespace std;

int main()

{
int i=20;
cout <<i<<" " <<i++<<" "<<i;
return 0;

}

when i pre increment 'i'. it gives

21 21 21

Please explain
1
2
3
4
int i=20; // i is equal to 20.

cout <<i<<" " <<i++<<" "<<i; // first it prints out i, which is 20. 
//Then it prints out i++, which is i + 1. then it prints out i again with is 20. 


If you thought that i++ permantently increases i then you're wrong. If you want to increase i. You do it like this

i = i + 1; or in a shorter way - i +=1
No i wanted to know the reason for this.
I wanted to know how i++ works in cout<<i++.

I read a book it says that calculations take place from right to left wherase printing from left to right.

Although when we use i++ in for loops , it is incremented permanently.
Hi

I would expect the output to be 20 20 21

1
2
int i=20;
cout <<i<<" " <<i++<<" "<<i; 


i = 20 at the start, the ++ being a suffix means it would output i as 20, then increment it, making the last i value 21.

Similarly i would expect ++i output to be 20 21 21, as it would increment i before output.

But when i ran it in codeblocks it gave 21 20 21 for i++
and 21 21 21 for ++i
If you thought that i++ permantently increases i then you're wrong.


i++ does increase i.

The problem here is that the order of evaluation of function arguments is undefined, because you are modifying i and reading it in between sequence points.
I am really a noob to understand sequence point n alll....:P
it is the problem about postfix and prefix. You can look up online.
Topic archived. No new replies allowed.