Question: diff. between ++i and i++

Hello all,

I'm currently really confused about this code:


1
2
3
i = 1;
cout << ++i << " " << i++; output: 3 1    (should be 2 1)?
cout << i++ << " " << ++i; output: 2 3    (should be 1 2)?


according to my textbook, since i = 1, then ++i should have 2 stored in i, and i++ should have 1 stored in i. This is the case when I output i individually, but how come when I try to output both i++ and ++i / vice-versa in one statement, the output seems to be completely off?


thanks
Your putting the entire command on one line which is causing your confusion.

Try
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	
int	i = 1;
cout << ++i  << endl;
i = 1;
cout << i++  << endl;

// not the same as 
i = 1;
cout << ++i  << endl;
// i = 1;
cout << i++  << endl;

return 0 ;
}
Last edited on
oh thank, i've tried to write the codes in separate lines and it's outputting correctly. But i'm just curious, why when I write everything on a single line, eg)
cout << ++i << " " << i++; the output is: 3 1 ?
Last edited on
The order in which function calls are evaluated is not guaranteed to be left to right.

consider this code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
int func1()
{
    std::cout << "func1" << std::endl;
    return 1;
}

int func2()
{
    std::cout << "func2" << std::endl;
    return 2;
}

int main()
{
    std::cout << func1() << func2() << std::endl;
    return 0;
}


on my computer the output I get is
func2
func1
12


But i'm just curious, why when I write everything on a single line, eg)
cout << ++i << " " << i++; the output is: 3 1 ?

You are making the assumption that ++i is evaluated first but c++ does not make this guarantee. The behavior here is undefined.
Last edited on
ohh i see! I got it now :)

Thank you all very much for the clarification.
Topic archived. No new replies allowed.