-1

I am executing this c program on gcc compiler and getting strange results.
So how is it possible

code:

#include<stdio.h>
int main()
{
  int i;
  i =10;
  printf(" %d %d %d  ",i++,i++,i);  //output : 11 10 12
  return 0;
}

as per me result should be 10 11 12 but I am getting 11 10 12.
How is it possible?

Jarod42
  • 203,559
  • 14
  • 181
  • 302

2 Answers2

1

In C++, the order of evaluation of function arguments is undefined so if you use the increment operator multiple times in the argument to a particular function there is no 'correct' answer, they may be evaluated in any arbitrary order.

mattnewport
  • 13,728
  • 2
  • 35
  • 39
  • i got what you said but if arguments are evaluated randomly then each time i execute program i should get different output as per order of evaluation of arguments but i get same result each time i execute program ,why? – Niravsinh Parmar Apr 23 '15 at 18:48
  • @ineevparmar: undefined != ramdomly. – Jarod42 Apr 24 '15 at 09:31
1

Please familiarize yourself with the concept of Sequence points. Only at such defined sequence points is guaranteed that all side effects of previous evaluations are performed. There are no sequence points between the list of arguments of a function. So, it leads to undefined behavior.

Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34