用比较变量作为参数对printf的解释 [英] Explaination for printf with comparing variables as arguments

查看:98
本文介绍了用比较变量作为参数对printf的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的测试中的输出

1 6 1

1 6 1

在上面的程序中,我期望输出为0 6 0.在某些编译器中,它给出此输出(例如Xcode),但在某些其他编译器中,它给出的输出为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.

考虑以下程序

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

我的测试中的输出

0 0 6 1 0

0 0 6 1 0

这个下面的程序给出了我期望的正确输出,即0 0 6 1 0 但是为什么上面的程序在大多数编译器中没有给出060的输出

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

推荐答案

C标准说:

C11:6.5(p2):

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);  

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

a的副作用没有顺序,因为标准说:

the side effect to a is unsequenced because standard says:

这篇关于用比较变量作为参数对printf的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆