用C在这个例子中的逻辑前pressions的短路行为 [英] Short circuit behavior of logical expressions in C in this example

查看:158
本文介绍了用C在这个例子中的逻辑前pressions的短路行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序

#include <stdio.h>

int main(void)
{
    int i, j, k;

    i = 1; j = 1; k = 1;

    printf("%d ", ++i || ++j && ++k);
    printf("%d %d %d", i, j, k);

  return 0;
}

观察

1 2 1 1

我期待1 1 2 2,为什么?因为和放大器;&安培;拥有超过|| precedence。于是我跟着下列步骤操作:
1)Ĵ加1,所以现在Ĵ值2 ...
 2)K加1,所以现在ķ值2 ...
 3)2及与放大器; 2,计算结果为1 ...
 4)无需进一步评估为一体的右操作数||是真实的,所以整个前pression必须,因为...

I was expecting 1 1 2 2. Why? Because the && has precedence over ||. So I followed these steps: 1) j added 1, so j now values 2... 2) k added 1, so k now values 2... 3) 2 && 2, evaluates to 1... 4) No need of further evaluation as the right operand of || is true, so the whole expression must be true because of short circuit behavior of logical expressions...

为什么我错了吗?

推荐答案

precedence只影响分组。 &放大器;&安培; 具有更高的precedence比 || 意思是:

Precedence affects only the grouping. && has a higher precedence than || means:

++i || ++j && ++k

相当于:

++i || (++j && ++k)

但是,这并不意味着 ++ J&安培;&安培; ++氏/ code>首先评估。它仍然从左向右计算,并根据 || 的短路规则+ I 是真实的,所以 ++ J&安培;&安培; ++氏/ code>不会求。

But that doesn't mean ++j && ++k is evaluated first. It's still evaluated left to right, and according to the short circuit rule of ||, ++i is true, so ++j && ++k is never evaluated.

这篇关于用C在这个例子中的逻辑前pressions的短路行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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