“==”评估为大于1的任何C编译器?

因为任何非零意味着都是真的,但是><==等运算符返回1表示true,我很好奇是否有任何值得注意的C编译器,这些运算符可能导致值大于1

换句话说,是否存在int i = (a==b) ; 如果我打算使用i不作为布尔值,而是作为整数,并假设它将是01 ,会导致未定义的行为?

不,如果有,它们不是C编译器:-)标准要求关系运算符和相等运算符返回1表示true,0表示false表示。


由C表示的积分值解释为布尔值的规则规定0为假,任何其他值为真。 请参阅C11有关if/while/do/for ,这些部分都包含"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.


但是,对于比较类型表达式,您将得到的结果非常明确,您可以获得01 。 这些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草案没有明确规定平等算子的返回值,但它确实说:

==(等于)和!=(不等于)运算符类似于关系运算符,除了它们的优先级较低。

关系运算符部分确实说明:

如果指定的关系为真,则每个运算符<(小于),>(大于),<=(小于或等于)和> =(大于或等于)将产生1,如果是,则为0假。

参考: 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)在7.6和7.7中也有相同的说法:“如果指定的关系为假,则[关系运算符]全部为0,如果为真,则为1。” ……“[等于运算符]与关系运算符完全类似,除了它们的优先级较低。”

他们保证返回01

参考:
C99标准:6.5.9平等运营商

第3段:

==(等于)和!=(不等于)运算符类似于关系运算符,除了它们的优先级较低.108) 如果指定的关系为真,则每个运算符产生1,如果为假,则产生0。 结果是int类型。 对于任何一对操作数,其中一个关系是正确的。

我认为这里的人不回答这个问题。 问题在于标准所说的内容,问题在于是否有任何值得注意的编译器在这方面不符合标准。

不,据我所知,没有。

我没有访问C标准,但根据维基百科 :

C使用整数类型,其中关系表达式如i> j和逻辑表达式通过&&和||连接 被定义为如果为真则值为1,如果为假则为0,而if,while,for等的测试部分将任何非零值视为真。

幸运的是,维基百科确实有正确的引用,但因为它们是书籍的参考,不知道有多少帮助:)。

据我所知,这是从C99标准的6.5.93段开始的

==(等于)和!=(不等于)运算符类似于关系运算符,除了它们的优先级较低.108)如果指定的关系为真,则每个运算符产生1,如果为假,则产生0。 结果是int类型。 对于任何一对操作数,其中一个关系是正确的。

因此,似乎评估值应为1或0

根据规范,要被视为C语言,条件运算符必须返回0表示false,1表示true表示。

以ha句forms:

 Specification Disallows this behavior, Otherwise not C. 

在c89 / c90 / ANSI-C之前,比较运算符保证在“假”条件下产生零值,否则不等于零。 很少需要c89引入的真正 “标准化”的替代品1 ,并且在需要的情况下,可以使用a = (b==c) ? 1 : 0; a = (b==c) ? 1 : 0;