-5

Why does this code shows the output as "3 2" instead of "2 3" ?

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
#include<vector>
using namespace std;
int main()
{

    int i=2;// declare

    printf("%d %d\n",i++,i++);//print
    return 0;
}

Output is : "3 2" Why it prints in reverse order

Engineero
  • 12,340
  • 5
  • 53
  • 75
user2665595
  • 9
  • 1
  • 1

2 Answers2

4

In this statement, the expression "printf(...)" modifies the variable "i" more than once without an intervening sequence point.

This behavior is undefined.

The compiler has detect a case where the same variable has been modified more than once in an expression without a sequence point between the modifications. Because what modification will occur last is not defined, this expression might produce different results on different platforms.

Rewrite the expression so that each variable is modified only once.

even you might get output "2 3" in different compiler

java seeker
  • 1,246
  • 10
  • 13
0

The order of evaluation of printf is from right to left in here

First evaluate

printf("%d %d\n",i++,i++);
           ^

Then

printf("%d %d\n",i++,i++);
         ^

So you got the output as 3 2

The behaviour will be definitely undefined due to the undefined evaluation order of parameters.

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55