cprintfstdiopostfix-operatorprefix-operator

Different and odd results when using prefix and postfix operators in function arguments


Code:

#include <stdio.h>

int main()
{
    int i = 3;
    printf("%d %d %d %d %d\n",i = 7,--i,i = 18, i+5, i = 0);
    printf("%d %d %d %d %d\n",i = 7,i--,i = 18, i+5, i = 0);

    return 0;
}  

Output:

7 7 7 5 7
7 18 7 5 7

Why I am getting this output, can anyone explain to me how are these expressions inside printf statements are executed?

I mean, in which order are considered by compiler?


Solution

  • The order of evaluation of arguments is unspecified, and unsequenced modifications to the same object has undefined behaviour.

    So, formally, reasoning about your code is meaningless.

    However, it is explainable with evaluation from the right, and not irrational or random.
    (Note that most of the arguments are the same as passing i; i = 18 "is" i, not 18.)

    The first:

    i = 0;
    int new_variable = i + 5;
    i = 18;
    i -= 1;
    i = 7;
    printf("%d %d %d %d %d\n", i, i, i, new_variable, i);
    

    The second:

    i = 0;
    int new_variable = i + 5;
    i = 18;
    int previous_i = i;
    i = 7;
    printf("%d %d %d %d %d\n", i, previous_i, i, new_variable, i);
    i -= 1;