#include<iostream>
using namespace std;
int main()
{
int i=2;
cout<<++i<<" "<<++i;
return 0;
}
Why the output of program is '4 4' not '3 4' ?
#include<iostream>
using namespace std;
int main()
{
int i=2;
cout<<++i<<" "<<++i;
return 0;
}
Why the output of program is '4 4' not '3 4' ?
because both increments occur before the line is output. the actual writing to the screen is delayed until the entire line has been run, but by then the reference for i has already had its value updated.
if you split your cout line into two discrete outputs, things would evaluate as you expect.
You have two side effects on the same variable (the two increments) with no sequence point between them. So they might happen in any order or might even get interleaved -- the behavior is undefined. You appear to be getting interleaved behaviors here -- the expression ++i
is increment I then read i. So you're getting increment, increment, read, read.