increment operator

int i=20
cout<<i<<i++<<++i;

what will be the output value of i?
It's undefined. The output could be anything.

This, on the other hand, will have fixed output:

1
2
3
4
int i=20;
cout<<i;
cout<<i++;
cout<<++i;


This outputs: 202022, and the value of i would be 22
why dont you try, the output would be
202121


@Disch why 22?
because you are incrementing 20 by one twice....
Last edited on
what? O_O why the output of this is 23222120
it should be 20212121,
1
2
int i=20;
cout<<i<<i++<<i++<<i++;

is it storing in every cout?
why the output of this is xxxxx
it should be yyyyy


It's undefined. The output could be anything.
Again to reiterate when Chervil and I have said:

this is undefined and the output can be anything.

This has been discussed and explained many times on this forum. You must not string together multiple increments or assignments on the same cout line. You must separate each one with a semicolon.

A previous post for reference:
http://www.cplusplus.com/forum/beginner/135021/

1
2
3
4
5
6
7
8
9
10
11
// BAD BAD BAD YOU MUST NEVER DO THIS
int i=20;
cout<<i<<i++<<i++<<i++;

// This is OK
int i=20;
cout << i;   // 20
cout << i++; // 20
cout << i++; // 21
cout << i++; // 22
 // at this point i==23 
Last edited on
I see... in the 2nd snippet in line 8 it storing the new value of i and it will only start storing if the ++ (incrementation) has performed. Therefore if only I then I then I the output would only be 20202020
Topic archived. No new replies allowed.