为什么不是“k”在语句“m = ++ i&&&& ++ j || ++ K"当“++ i&& ++ j”评估为真? [英] Why isn't "k" incremented in the statement "m = ++i && ++j || ++k" when "++i&&++j" evaluates to true?

查看:155
本文介绍了为什么不是“k”在语句“m = ++ i&&&& ++ j || ++ K"当“++ i&& ++ j”评估为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在逻辑运算符应用于其结果之前,复合逻辑 AND / OR 表达式中的单个表达式是否不应先被评估?为什么 ++ k 不变的条件 m = ++ i&& ++ j || ++ k 为以下程序:

Aren't the individual expressions in a composite logical AND/OR expression supposed to be evaluated first before the logical operators are applied to their result?Why is ++k untouched in the condition m = ++i && ++j || ++k for the following program :

 #include<stdio.h>

 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,3,0, 1

Output : -2,3,0,1

但我预计输出 -2,3,1,1

推荐答案

你应该避免编码这样不可读的代码。它实际上被解析为

You should avoid coding such unreadable code. It is actually parsed as

m = (++i && ++j) || ++k;

所以一旦 j> = 0 ++ j 条件始终为真,因此& & 是一个简短的,然后,但 || 是一个简短的 / em>(所以他们可能不会评估他们的正确操作数)。

So once j >= 0 the ++j condition is always true, so ++k is not evaluated since && is a short-cutting and then but || is a short-cutting or else (so they may not evaluate their right operand).

所以&& 被评估为遵循:左操作数被评估,如果它是false它被返回,然后只有当它是真的(即不等于 0 )时,正确的操作数被评估和返回作为&& 的评估结果。同样 || 的评估如下:左操作数被评估。如果它是真的(非零),它将成为 || 的结果;否则正确的操作数被评估,并且是 || 表达式的结果。

So && is evaluated as follow: the left operand is evaluated, if it is false it is returned, and then only when it is true (i.e. not equal to 0) the right operand is evaluated and returned as the evaluated result of the &&. Likewise || is evaluated as follow: the left operand is evaluated. If it is true (non-zero) it becomes the result of the ||; or else the right operand is evaluated and is the result of the || expression.

特别是,当编码 if(x> 0&< 20 / x< 5)从来没有为 x == 0

In particular, when coding if (x > 0 && 20/x < 5) the division is never attempted for x==0 .

还阅读维基百科运营商C& C ++ & 短路评估& 懒惰评估页面;请花几个小时阅读一本好的C编程书。

Read also the wikipedia operators in C & C++ & short circuit evaluation & lazy evaluation pages; and please take several hours to read a good C programming book.

这篇关于为什么不是“k”在语句“m = ++ i&amp;&amp;&amp;&amp; ++ j || ++ K&QUOT;当“++ i&amp;&amp; ++ j”评估为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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