可以比较布尔运算的结果吗?

时间:2012-05-08 10:10:41

标签: c operators standards

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

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

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

3 个答案:

答案 0 :(得分:7)

是的,虽然C的布尔值的解释规则是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.

这涵盖了您在问题中明确提到的所有内容。我能想到的唯一一个其他布尔操作(在我的脑海中)是逻辑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中涉及ifwhiledofor的部分,这些部分都包含语言如果/ "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.

答案 1 :(得分:1)

运算符生成的值对于true始终为1,对于false为0。

答案 2 :(得分:0)

的结果
  • 否定运算符(!

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

  • 相等运算符(==!=

    逻辑运算符(&&||

int(false)或0(true)的1值。