Pau*_*nta 3 c standards operators
请问C标准保证了布尔运算(==,!=,>,&&,||,等)总是具有相同的值来表示真实性?换句话说,如果是真的,它们是否总是返回一些正常数,或者它是唯一保证它是正数的唯一保证?
我问这个的原因是要知道下面的陈述是否有效.如果两个指针都是NULL或两个指针指向某处(不一定是同一个地方),那么该表达式应为true.
if ((ptr1 == NULL) == (ptr2 == NULL))
Run Code Online (Sandbox Code Playgroud)
是的,尽管由C表示的积分值解释为布尔值的规则为0false且任何其他值为真(a),但比较运算符的结果始终为1或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.
(一):见C11部分处理if,while,do和for,其中都包含语言沿着东西线发生,如果/当"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.