1
#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' ?

Shubham Jaiswal
  • 15
  • 1
  • 1
  • 4

2 Answers2

0

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.

Frank Thomas
  • 2,434
  • 1
  • 17
  • 28
0

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226