Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top