cprintf

What is the order of evaluation of printf(..) parameters?


I want to do something like this printf("%d,%d", array[c], array[c+1]), with only one variable that increases in every iteration. I wrote the following code, and I expected "1,2" to stdout, I was wrong:

#include <stdio.h>
int main()
{
    int c = 1;
    printf("%d,%d",c++,c++); /* 2,1 */
    //printf("%d,%d",c,c++);   /* 2,1 */
    //printf("%d,%d",c++,c);   /* 1,2 */
}

If I try doing printf("%d,%d",c++,c) and printf("%d,%d",c,c++), I can see that there is no defined order of execution of the "c++" statements.

Could somebody explain how the code I wrote compiles to ? And why and how does it change according to the position of the "c++" statements.


Solution

  • The order of evaluation of the arguments in a function call is unspecified, and there is no sequence point between the evaluation of these expressions. This means that - if one expression alters as a side effect an object (like the value of c) which is also accessed by another expression - it is unpredictable what the outcome of these expressions will be. For that reason, the language defines such cases as undefined behaviour (cf., for example, this online C standard draft):

    6.5 Expressions

    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. ...