0

`

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

`

The output is - 11 11

How is it evaluated??

1 Answers1

0

This is undefined behaviour, so the result could be anything. There is no sequence point in the line, which means that both operations are unsequenced - either argument could be evaluated first, or both simultaneously (see https://en.wikipedia.org/wiki/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?

CoderMuffin
  • 519
  • 1
  • 10
  • 21
  • 2
    The "For example, if `a` is evaluated first" is nonsensical and obscures the point. The inherent issue is that `a` is *not* evaluated before `++*ptr`, nor after, nor even at the same time. The evaluations of those two expressions are *unsequenced* relative to each other as far as C semantics are concerned. And because they are unsequenced and one has a side effect on an object read by the other, the behavior is undefined. – John Bollinger Dec 05 '22 at 19:24
  • Thanks for the info, I have removed it and tried to improve the answer – CoderMuffin Dec 06 '22 at 07:43