-4
int x=10;
printf("%d %d %d\n",x,++x,x++);
printf("%d %d %d",x,x+20,x+30);

It is printing output as

12 12 10
12 32 42

Why the order in first printf is in reverse order and why not in second printf statement? i found in a book that C uses reverse printing order.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Rakesh
  • 133
  • 1
  • 8
  • 1
    or... [Undefined Behavior and Sequence Points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points), and likely many others. – WhozCraig Apr 14 '14 at 20:04
  • During evaluation, first it will take all the values starting from right into the stack. If the variable has any post/pre increment, it evaluates and stores the value. Else, it stores as a variable in the stack and takes the final value of the var. right most x++ - 10, because its post inc updates x as 11. for ++i - 12, pre inc and updates x as 12 for x as it is in the stack. Final output will be 12 12 10 which is the order of retrieving from stack. – Dinesh Jan 19 '18 at 15:53

1 Answers1

2

Your code has undefined behavior ("UB"). Thus, anything can happen.

Specifically, the rule violated is that one must not read and write the same variable without sequence-point except to determine the value to write.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • As comment length is limited i have rephrased the statement as printf("%d %d %d %d",i,++i, i++,i); with i=1 During evaluation, first it will take all the values starting from right into the stack. If the variable has any post/pre increment, it evaluates and stores the value. Else, it stores as a variable in the stack and takes the final value of the var. right most i - i in to the stack, for i++ - 1 because its post inc updates i as 2. for ++i - 3, pre inc and updates i as 3 for i as it is in the stack. for var as i in stack takes final value of i as 3. Final output will be 3 3 1 3 – Dinesh Jan 19 '18 at 15:49
  • @Dinesh: That does not follow from the standard... – Deduplicator Jan 19 '18 at 16:04
  • printf follows the rule which i specified above. there is not such sperate rule for the varibales changed and unchanged. – Dinesh Jan 19 '18 at 16:32
  • @Dinesh: Did you ever read the standard, or the other posts linked above? – Deduplicator Jan 19 '18 at 17:37