Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...