c++ - 使用逻辑运算符时无法理解执行情况

标签 c++ c logical-operators

这是代码:

void main()
{
    clrscr();
    int a=-3 , b=2 , c=0, d;
    d = ++a && ++b || ++c;
    printf("a=%d , b=%d , c=%d, d=%d ",a,b,c,d);
    getch();
}

输出:-2 , 3 , 0 , 1

我无法理解为什么 c 的值没有递增,我想应该是1 d = 1 的输出是怎么来的? .

最佳答案

声明;

d = ++a && ++b || ++c;

从左到右分组(给定 precedence of && );

d = (++a && ++b) || ++c;

因此,在计算 && 时,由于第一个操作数为 true(++a),因此计算第二个操作数(++b)。此时,这个逻辑与的结果是true;因此,逻辑“或”为真,并且不计算第二个操作数(++c)。

这种行为是有保证的,通常称为短路评估。 C++ 和 C 标准中的措辞是 listed here, in this answer ;此处针对 C++ 进行了简要复制;

§5.14 逻辑 AND 运算符

1 The && operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

§5.15 逻辑或运算符

1 The || operator groups left-to-right. The operands are both contextually converted to bool (Clause 4). It returns true if either of its operands is true, and false otherwise. Unlike |, || guarantees left-to-right evaluation; moreover, the second operand is not evaluated if the first operand evaluates to true.

关于c++ - 使用逻辑运算符时无法理解执行情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35941429/

相关文章:

c++ - C++ 中的私有(private)继承可见性/访问

c++ - 动态内存分配

c - C 中的内部短路评估

r - 识别列表中的 TRUE block

MySQL 条件相反

c++ - 对从串口接收到的字符串进行分段

python - 在python中,为什么要使用函数来获取类成员?

c - 反汇编 C 代码

c - 如何将所有 C 文件编译成对象并将其放在子目录中

c++ - 预取大量引用数据的实际限制