gpt4 book ai didi

bool 运算的结果可以比较吗?

转载 作者:太空狗 更新时间:2023-10-29 15:59:18 25 4
gpt4 key购买 nike

C 标准是否确保 bool 运算 (==, !=, >, && , ||, etc) 总是有相同的值来表示真实性?换句话说,如果为真,它们是否总是返回一些正常数,或者唯一保证它将是正数?

我问这个问题的原因是想知道下面的陈述是否有效。如果两个指针都为 NULL 或者两个指针都指向某个地方(不一定是同一个地方),则该表达式应该为真。

if ((ptr1 == NULL) == (ptr2 == NULL)) 

最佳答案

是的,尽管 C 将整数值解释 为 bool 值的规则规定 0为假且任何其他值为真(a),比较运算符的结果总是10 .

所以表达式 (a == b)永远不会给你42 ,例如。

标准(C11)的相关位都在6.5 Expressions下:

6.5.8/6: Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.

6.5.9/3: The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false.

6.5.13/3: The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0.

6.5.14/3: The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0.

这涵盖了您在问题中明确提到的所有内容。我能想到的唯一其他 bool 运算(在我的脑海中)是逻辑 NOT 运算符 !这也包括在内:

6.5.3.3/5: The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.


(a):参见处理 if 的 C11 部分, while , dofor ,其中都包含如果/同时发生某事的语言 "the expression compares unequal to zero" .具体来说:

6.8.4.1/2: In both forms [of the if statement, one with and one without an else clause], the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.

6.8.5/4: An iteration statement [while, do and for] causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.

关于 bool 运算的结果可以比较吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10496603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com