3

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

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

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

3 回答 3

7

是的,尽管C 将整数值解释为布尔值的规则声明0为 false 并且任何其他值为 true (a),但比较运算符的结果始终为1or 0

因此,例如,表达式(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.

这涵盖了您在问题中明确提到的所有内容。我能想到的唯一其他布尔运算(在我脑海中)是逻辑 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):参见 C11 中处理 、 和 的部分if,它们while都包含类似于 if/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.

于 2012-05-08T10:13:45.557 回答
1

是的。

运算符生成的值将始终为 1 表示真,0 表示假。

于 2012-05-08T10:11:40.480 回答
0

结果

  • 否定运算符 ( !)

  • 关系运算符 ( <, >, <=, >=)

  • 等式运算符 ( ==, !=)

    逻辑运算符 ( &&,   ||)

是(false) 或(true)的int值。01

于 2012-05-08T10:19:28.620 回答