Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

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

I read here that there is a sequence point:

After the action associated with input/output conversion format specifier. For example, in the expression printf("foo %n %d", &a, 42), there is a sequence point after the %n is evaluated before printing 42.

However, when I run this code:

int your_function(int a, int b) {
    return a - b;
}

int main(void) {
    int i = 10;

    printf("%d - %d - %d
", i, your_function(++i, ++i), i);
}

Instead of what I expect I get:

12 - 0 - 12

Meaning that there was not a sequence point created for the conversion format specifier. Is http://en.wikipedia.org wrong, or have I just misunderstood something, or is gcc non-compliant in this case (incidentally Visual Studio 2015 yields the same unexpected result)?

EDIT:

I understand that the order the arguments to your_function are evaluated and assigned to the parameters is undefined. I'm not asking about why my middle term is 0. I'm asking why the other two terms are both 12.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 1, &x, 2, &x);

even though the value of x is modified twice.

But this code is UB:

int x = 1;
printf("%d %d
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...