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
241 views
in Technique[技术] by (71.8m points)

c - Explaination for printf with comparing variables as arguments

main(){
    int a = 5;
    int b = 6;
    printf("%d %d %d",a==b,a=b,a<b);
}

Output in my testing

1 6 1

In above program I am expecting output as 0 6 0 . In some compilers it is giving this output (e.g. Xcode) but where as in some other compilers it is giving output as 1 6 1 . I couldn't find the explanation . It is also the case of Sequence point.

Consider this below program

main(){
    int a = 5;
    int b = 6;
    printf("%d %d %d",a<b,a>b,a=b);
    printf("%d %d",a<=b,a!=b);
}

Output in my testing

0 0 6 1 0

this below program is giving the correct output which i am expecting which is 0 0 6 1 0 but why the above program is not giving the output as 060 in most of the compilers

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C standard says:

C11: 6.5 (p2):

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined [...]

This means your program invokes undefined behavior. In the statements

printf("%d %d %d",a==b,a=b,a<b);  

and

printf("%d %d %d",a<b,a>b,a=b);

the side effect to a is unsequenced because standard says:


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

...