因为任何非零都表示为真,但是 >
, <
, ==
等运营商返回 1
事实上,我很好奇是否有任何著名的 C 编译器,其中这些运算符可以产生大于 1
的值.
换句话说,有没有编译器在哪里 int i = (a==b)
;如果我打算使用 i
会导致未定义的行为不是 bool 值,而是整数,并假设它是 0
或 1
?
最佳答案
不,即使有,它们也不是 C 编译器:-) 标准要求关系运算符和相等运算符返回 1 表示真,0 表示假。
C 将整数值解释 为 bool 值的规则指出 0
为假,任何其他值为真。请参阅处理 if/while/do/for
的 C11 部分,它们都包含类似 "while 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.
但是,对于比较类型的表达式,您将得到什么结果是非常明确的,您要么得到 0
或 1
.这些 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.
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.
而且这种行为方式可以追溯到 C99 和 C89(ANSI 时代)。处理关系运算符和相等运算符的 C99 部分还声明返回值为 0 或 1。
而且,虽然 C89 草案没有明确规定相等运算符的返回值,但它确实说:
The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence.
关系运算符部分确实声明:
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.
引用:http://flash-gordon.me.uk/ansi.c.txt因为我周围没有任何 C89 标准的副本。我确实有第二版 K&R(1988 年的 ANSI 版本),在引用手册附录 A 的 A7.9 和 A7.10 节中基本上说了同样的事情。如果您想从第一版中得到明确的答案,那必须来自妻子不太愿意扔旧垃圾的人。
附录:
根据 Michael Burr 的说法,在保留旧书方面,他要么未婚,要么有一个比我更乐于助人的妻子 :-)
K&R 1st Edition (1978) also says the same in 7.6 and 7.7: "The [relational operators] all yield 0 if the specified relation is false and 1 if it is true." ... "The [equality operators] are exactly analogous to the relational operators except for their lower precedence."
关于c - "=="的计算结果大于 1 的任何 C 编译器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10632237/