-2

As printing will start from left side to right side in cout function, why these types of commands printing differently? please explain me. According to my knowledge the output of the following program should be 113 but it is 322. How?

#include<iostream.h>
void main()
{
int i=1;
cout<<i<<i++<<++i;
}

Output:

322

Thanks in Advance.

tripleee
  • 175,061
  • 34
  • 275
  • 318
Vishnu Vardhan
  • 47
  • 1
  • 1
  • 6

1 Answers1

0

You seem to be assuming that the increments happen from left to right, but according to the Standard, the order of evaluation of subexpressions is unspecified. See here for more details.

In this case, it looks like the compiler chose to evaluate from right to left:

  • ++i happens, so i == 2 and 2 is the value of the expression;
  • i++ happens, incrementing i to 3 but evaluating to its old value, 2;
  • i is now evaluated as 3.
Thomas
  • 174,939
  • 50
  • 355
  • 478