-3

I executed following following code.


int main(void)
{
    int c;
    c=0;
    printf("%d..%d..%d \n", c,c,c);
    c=0;
    printf("%d..%d..%d \n", c,c,c++);
    c=0;
    printf("%d..%d..%d \n", c,c++,c);
    c=0;
    printf("%d..%d..%d \n", c++,c,c);

return 0;}

I expected the output as

0..0..0

1..1..0

0..1..0

0..0..0

But the output(compiled with gcc) was

0..0..0

1..1..0

1..0..1

0..1..1

What is wrong with my expectation? In gcc ,evaluation order is from right to left. Is It?

Shihab
  • 531
  • 1
  • 12
  • 25
  • What happens if you make all incremented, all 3 of them? Does it print 3,2,1 ? – huseyin tugrul buyukisik Jul 28 '13 at 10:59
  • I would mark this as a duplicate except the duplicates I found were older than the C 2011 standard, and we ought to have an updated answer for the new standard. Is there another question covering this topic that addresses the C 2011 standard? – Eric Postpischil Jul 28 '13 at 11:59

1 Answers1

5

What is wrong with my expectation?

Evaluation order of function parameters is not specified - it is left up to the implementation. Moreover, there is no sequence point * between the parameters, so using a modified parameter again before a sequence point cannot give you a predictable result: it is undefined behavior (thanks, Eric, for providing a reference to the standard).

If you want a particular evaluation order, you need to evaluate your parameters as full expressions (that forces a sequence point between each of them):

int arg1 = c++;
int arg2 = c;
int arg3 = c;
// This: printf("%d..%d..%d \n", c++,c,c);
// Becomes this:
printf("%d..%d..%d \n", arg1, arg2, arg3);


* Sequence point is a fancy name for a place in code after which you can count on side effects, such as increments or decrements, of all preceding expressions to have been applied.
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • how to specify evaluation order of function? – Shihab Jul 28 '13 at 11:07
  • @Shihab You can force evaluation order by evaluating each parameter separately. – Sergey Kalinichenko Jul 28 '13 at 11:12
  • 2
    This is not merely a matter of unspecified evaluation order. The entire behavior is undefined by the C standard, not just the order in which the parameters are evaluated. Per C 2011 (N1570) 6.5 2: “If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.” – Eric Postpischil Jul 28 '13 at 11:53
  • @EricPostpischil Thanks for providing a reference! – Sergey Kalinichenko Jul 28 '13 at 11:58