布尔表达式中 print 函数的行为

behavior of print function inside a Boolean expression

语言:C

如果输入 0,布尔表达式输出 0,否则输出 1。

根据上述声明,

案例 1:

输入

#include <stdio.h>
#include <stdbool.h>
main()
{
    int a = 1,
        b = 2;
    bool res = ((a == b) && ("your "));
    printf("res = %d", res);
}

输出

res = 0

案例 2:

输入

    bool res = (!(a == b) && ("your "));
    printf("res = %d", res);

输出

res = 1

案例 3: 现在我将 prinf 函数添加到 ("your ")

输入

    bool res = ((a == b) && printf("your "));
    printf("res = %d", res);

输出

res = 0 //adding printf doesn't change the output

案例 4: 输入

    bool res = (!(a == b) && printf("your "));
    printf("res = %d", res);

输出

your res = 1 // i expected just "res = 1" not "your res = 1"

为什么print函数在CASE 3中不执行,而在CASE 4中执行?

逻辑与运算符&&的求值是短路求值

考虑A && B,首先评估A。当 A 为真时,A && B 可以变为真并计算 B。当 A 为假时,A && B 永远不会为真并且 B 不会被评估。

现在来看实际案例

在案例 3 (a == b) && printf("your ") 中,(a == b) 为假,因为 a (1) 不等于 b (2)。因此现在我们失去了表达式 (a == b) && printf("your ") 变为真的所有机会,因此 printf("your ") 没有被计算。这意味着该功能未执行。

在案例 4 !(a == b) && printf("your ") 中,!(a == b) 为真,因为 (a == b) 为假。现在表达式 !(a == b) && printf("your ") 可能会根据 printf("your ") 的值变为真,因此计算 printf("your ") 并执行函数。

情况 3:

这是由于编译器优化了语句。由于括号的使用,该语句从左到右翻译和计算。第一个表达式是:(a == b) 由于 a 和 b 的值而为假。编译器发现 ((a == b) && printf("your")) 中表达式的结果将始终为 false。因此优化决定不为 printf("your") 生成代码。 我敢打赌,如果你在 demode 模式下编译它,你会看到预期的结果。

案例4的解释留给你自己。这很明显。 (提示注意运算符“!”、“&&”的优先级)

祝你好运。

根据 C 标准(6.5.13 逻辑与运算符)

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

在此声明中用作初始值设定项的表达式中

bool res = ((a == b) && printf("your "));

逻辑 AND 运算符的第一个操作数 (a == b) 的计算结果为 0。因此,调用 printf 的第二个操作数未计算,

另一方面,在此表达式中用作声明中的初始值设定项

bool res = (!(a == b) && printf("your "));
 

第一个操作数 !(a == b) 的计算结果为 1。因此,调用 printf 的第二个操作数也被计算。