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

vsz*_*vsz 11 c undefined-behavior

作为任何非零值意味着真实的,但是>,<,==等运营商回归1真正的,我如果有任何显着的C编译器,当这些运营商可能会导致的值大于好奇1.

换句话说,是否有任何编译器int i = (a==b); 如果我打算不使用i不作为布尔值,而是作为一个整数,并假设它将是0或者1?会导致未定义的行为

pax*_*blo 19

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


C表示布尔值的积分值解释规则为0false,其他任何值都为真.参见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.


但是,对于比较类型的表达式,你会得到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草案没有明确规定平等算子的返回值,但它确实说:

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

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

如果指定的关系为真,则每个运算符<(小于),>(大于),<=(小于或等于)和> =(大于或等于)将产生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." ......"[等于运算符]与关系运算符完全相似,只是它们的优先级较低."

  • K&R 1st Edition(1978)在7.6和7.7中也说相同:“ [关系运算符]如果指定的关系为false,则全部为0,如果为真,则为1。” ...“ [等式运算符]完全类似于关系运算符,只是它们的优先级较低。” 因此,我认为这种行为对于除奇数C编译器以外的所有代码都适用。请记住,可能不会每天都在诸如a + =(b == c)之类的算术表达式中使用关系运算符或相等运算符的结果,但是它们很常见。他们可能在当时更普遍。 (2认同)

Alo*_*ave 9

他们保证返回01.

参考:
C99标准:6.5.9平等操作员

第3段:

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