Ayush Chothe
Ayush Chothe

Reputation: 9

What is the order of evaluation in printf() for pointers?

Consider:

a = 10;
int *ptr = &a;
printf("%d %d\n", a, ++*ptr);

The output is - 11 11

How is it evaluated?

Upvotes: -2

Views: 90

Answers (1)

CoderMuffin
CoderMuffin

Reputation: 608

This is undefined behaviour, so the result could be anything. There isn't any sequence point in the line, which means that both operations are unsequenced; either argument could be evaluated first, or both simultaneously (see Sequence point and John Bollinger's comment).

For example, when evaluating with the clang compiler, this is the output:

<source>:5:26: warning: unsequenced modification and access to 'a' [-Wunsequenced]
    printf("%d %d\n", a, ++a);
                      ~  ^
1 warning generated.
Execution build compiler returned: 0
Program returned: 0
2 3

See this answer for more: Order of operations for pre-increment and post-increment in a function argument?

Upvotes: 0

Related Questions