Sequence Points between printf function args; does the sequence point between conversions matter?

后端 未结 3 1360
轻奢々
轻奢々 2020-12-10 14:24

I read here that there is a sequence point:

After the action associated with input/output conversion format specifier. For example, in the expression

3条回答
  •  無奈伤痛
    2020-12-10 14:29

    I think you misunderstood the text about the printf sequence points (SP). They are somehow an anomaly, and only with %n because this format specifier has side effects, and those side effects need to be sequenced.

    Anyway, there is a SP at the beginning of the execution of printf() and after the evaluation of all the arguments. Those format-specifier SP are all after this one so they don't affect your problem.

    In your example, the uses of i are all in function arguments, and none of them are separated with sequence points. Since you modify the value (twice) and use the value without intervening sequence points, your code is UB.

    What the rule about the SP in printf means is that this code is well formed:

    int x;
    printf("%d %n %d %n\n", 1, &x, 2, &x);
    

    even though the value of x is modified twice.

    But this code is UB:

    int x = 1;
    printf("%d %d\n", x, ++x);
    

    NOTE: Remember that %n means that the number of characters written so far is copied to the integer pointed by the associated argument.

提交回复
热议问题