1

I am unable to understand the below issues while pre-incrementing and post-incrementing a variable inside printf:-

code used in turbocpp compiler:-

#include<stdio.h>
main()
{
int i=0;
clrscr();
printf("%d %d %d",i,i++,++i);
getch();
return(0);
}

the output in MSdos Compiler is :- 2 1 1

but for the same program in DevC++ 5.11 the output is:- 2 1 2

1) My understanding is printf prints by taking left variable first and then moves to right.(i have verified it using 3 different variables.) So, according to that shouldn't the output be 0 0 2?

2) I tried with DevC++ to check the output of the same program but it gave a different result. Now I am really confused as what should be the output.

3) Also if I vary:- printf ("%d %d %d", i,++i,i++); the output is 2 2 0.

I am not getting what is going on here. Somebody Please help me to understand better...

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Please change your program to use separate `printf` statements: `printf("%d\n", i); printf("%d\n", i++); printf("%d\n", ++i); printf("%d\n", i);`. Then everything should be clear, and well-defined, and make sense. – Steve Summit Mar 05 '16 at 21:33
  • that I already tested.. BTW thanks for replying. – whatsinaName Mar 05 '16 at 21:34

2 Answers2

1

Having two side effects on the same variable will give you an undetermined result, as each compiler is free to choose the order in which it evaluates the arguments.

1.9/15: If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

So it could for example be:

  • 0,0,1 if evaluated left to right
  • 2,1,1 if evaluated right to left
  • 2,1,2 if pre-increment is done on i and stored in i, then i is loaded as second argument and post incremented, then i is taken ans third argument (the compiler assuming that preincrement was already done), and then i is taken as first argument.

But other combinations could also be plausible. And undefined behaviour means really undefined, so perhaps one day this could even crash (if one say a compiler would automatically generate parallel code and 2 cores access to the same variable in the same time)

Christophe
  • 68,716
  • 7
  • 72
  • 138
0

C++ doesn't standardize the order in which function arguments are calculated, that's why results differ from compiler to compiler. See C++ Standard, section 5.2.2/8:

The order of evaluation of arguments is unspecified.

CodeFuller
  • 30,317
  • 3
  • 63
  • 79