开发者

printf and ++ operator [duplicate]

This question already has answers 开发者_Go百科here: Why are these constructs using pre and post-increment undefined behavior? (14 answers) Closed 3 years ago.

#include<stdio.h>
main()
{
    int a=10;
    printf("\n %d %d", a, a++); //11 10
    a=10;
    printf("\n %d %d", a++, a); //10 11
    a=10;
    printf("\n %d %d %d ", a, a++,++a); //12 11 12
}

after running this I got the output given in comments. as far as I know first output is expected because execution of printf goes from right to left but could not understand second and third


Nothing goes "from right to left" in function argument evaluation. When function arguments are evaluated, the order of evaluation is unspecified and there are no sequence points between evaluating separate arguments. This means that there's absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.

However, your code suffers from even worse problems. All three statements that call printf produce undefined behavior (UB) because they either make an attempt to modify the same object (a) twice without a sequence point between the modifications (the third call), or they attempt to modify an object and read it for an independent purpose (the first and the second call). So, it is too early to even mention the order of evaluation. Your code's behavior is undefined.


None of the outputs can really qualify as unexpected. All the arguments to a function are evaluated before entry to the function itself -- but the order of their evaluation relative to each other is unspecified, so all of these results are allowed. Officially, your last one (that has two separate instances of incrementing a) has undefined behavior, so it doesn't have to do anything sensible at all.


++a means increment a first, and then return evaluate the expression. (a changes, and the expression evaluates as a + 1)

a++ means evaluate a (so, erm, a), and then increment it. So a is passed, but the value of a is then (ie afterwards) changed to a+1.


You are invoking undefined behaviour by referencing both 'a' and 'a++' in the argument list.

It is not defined which order the arguments are evaluated in. Different compilers may choose different orders. A single compiler can choose different orders at different times.

Do not do it!


Function parameters are not evaluated in a defined order in C. Therefore one cannot tell beforehand if a or a++ will be evaluated first when calling printf.

See Parameter evaluation order before a function calling in C

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜