OR和AND在C温度范围 [英] OR and AND operation in C

查看:181
本文介绍了OR和AND在C温度范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的程序一个疑问。

I have a doubt in the program below.

int main()
{
    int i = -3,j = 2, k = 0,m;
    m = ++i || ++j && ++k;
    printf("%d %d %d %d\n", i, j, k, m);
    return 0;
}

我得到的输出 -2 2 0 1

在或操作,如果第一个值是真实的,那么它不会评价:第二个让 I = -2 J = 2
然后是与运算。它会检查这两个值,如果被true.So K = 1 然后 M = 1
所以输出应该是 -2 2 1 1 。我运行和检查,并得到为输出-2 2 0 1 ,但我不明白为什么。

In OR operation if 1st value is true then it won't evaluate the 2nd one so i = -2 and j =2. Then comes the AND operation . It will check for both the value to be true.So if k = 1 then m = 1. So the output should be -2 2 1 1. I run and check and got output as -2 2 0 1 but I could not understand how.

推荐答案

您使用的短路或。因为++ i的计算结果为-2,这是不为0,短路和不评估前pression的其余部分。其结果是,既不J或K得到递增。

You used a short circuit or. Since ++i evaluates to -2, which is not 0, it short circuits and doesn't evaluate the rest of the expression. As a result, neither j or k get incremented.

还要注意的是短路的运营商,||和&功放;&放大器;,是左关联的||高precedence比&安培;&放;.其结果是,在||如果左侧的值为true,首先得到评估,及早出局,而与放大器;&安培;早出局,如果左侧的值为false。

Also note that the short circuit operators, || and &&, are left associative and that || is higher precedence than &&. As a result, the || gets evaluated first, and early outs if the left hand side evaluates to true, while && early outs if the left hand side evaluates to false.

编辑:修正了解释precedence错误

Fixed a mistake with explaining the precedence.

这篇关于OR和AND在C温度范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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