-1

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

I have heard that printf function executes from right to left and prints from left to right. By that convention, the following program should give 7,6,5. But it's giving 7,7,7 on my linux gcc compiler. Is it compiler dependent?

int i=5;
printf("%d %d %d\n",++i,++i,i);

Also, can we use cdecl/pascal keyword to change the order of execution of printf? If yes, how do we do that? I have been trying to do this but without success. Thanx in advance!

Community
  • 1
  • 1
Ashwyn
  • 659
  • 1
  • 6
  • 18

2 Answers2

1

There is no order dictated by the standard in function calls, so the arguments can be evaluated in any order the compiler seems fit. So if you have side effects in the evaluation of the parameters, you get undefined behavior.

Attila
  • 28,265
  • 3
  • 46
  • 55
  • Specifically, if you have side effects that affect other parameters. `++i` is defined behavior as long as there are no other parameters who's evaluation depends on `i`. – Aaron Dufour May 21 '12 at 21:39
1

The evaluation order in your code is undefined, as there are no sequence points. You cannot relay on the evaluation order of function arguments, and you cannot change it either.

Check http://www2.research.att.com/~bs/bs_faq2.html#evaluation-order

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • perhaps because i am using increment on sam variable without sequence point, but if we use differnt variables, will the order of evaluation be as i have written? – Ashwyn May 21 '12 at 17:23
  • @Ashwyn: Nope, you can think of the evaluation order as "totally random". – K-ballo May 21 '12 at 17:27