Home > front end >  How to specify printf() what to evaluate first?
How to specify printf() what to evaluate first?

Time:04-23

This is the code, When I run this on vsode it runs smoothly without any warning, But running it on android apps like cxxdroid shows the warning at line printf("%d %d %d\n", (*p) , (*p) , *( p)); unsequenced modification and access to 'p', and both the compiler returning different output as follows below main() body:

#include <stdio.h>

int main() {
    int a[] = {10, 11, -1, 56, 67, 5, 4};
    int *p, *q;
    p = a; 
    q = a   3;

    printf("%d %d %d\n", (*p)  , (*p)  , *(  p));
    printf("%d\n", *p);
    printf("%d\n", (*p)  );
    printf("%d\n", (*p)  );
    q--;
    printf("%d\n", (*(q   2))--);
    printf("%d\n", *(p   2) - 2);
    for (int j = 0; j < 7; j  ) {
        printf("%d, ", a[j]);
    }
    printf("%d\n", *(p   -2) - 1);
    
    return 0;
}

vscode output:

12 11 11
13
13
14
67
54
10, 15, -1, 56, 66, 5, 4, 198

cxxdroid output:

10 11 11
11
11
12
67
54
12, 13, -1, 56, 66, 5, 4, 198

CodePudding user response:

Simply change

printf("%d %d %d\n", (*p)  , (*p)  , *(  p));

to

printf("%d ", (*p)  );
printf("%d ", (*p)  );
printf("%d\n", *(  p));

and the like.

Within a single expression, like printf("%d %d %d\n", (*p) , (*p) , *( p)), there are very few guarantees about evaluation order. But when you have completely separate statements (that is, with semicolons ; in between them), the order of evaluation of those statements is perfectly guaranteed.

See also Why are these constructs using pre and post-increment undefined behavior?
See also Why does a=(b ) have the same behavior as a=b ?

CodePudding user response:

To change printf("%d %d %d\n", (*p) , (*p) , *( p)); to have a defined order of evaluation that you select, use temporary variables:

int argument1 = (*p)  ;
int argument2 = (*p)  ;
int argument3 = *(  p);
printf("%d %d %d\n", argument1, argument2, argument3);

Put the first three statements in the order you choose.

  • Related