是“真实的”吗? >、<、!、&&、|| 的结果或 == 定义?
例如,当我用 C 语言编写 7>1
时(如果这不是一个始终存在的功能,则称为 C99),我是否可以期望结果恰好为 1 或者只是某个非零值?这适用于所有布尔运算符吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
例如,当我用 C 语言编写 7>1
时(如果这不是一个始终存在的功能,则称为 C99),我是否可以期望结果恰好为 1 或者只是某个非零值?这适用于所有布尔运算符吗?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
在 C99 §6.5.8 关系运算符中,第 6 项(
<
、>
、<=
和>=< /代码>):
至于相等运算符,在 §6.5.9 中更进一步(
==
和!=
):逻辑 AND 和逻辑 OR 在 §6.5.13 (
&&
) 中更进一步...和§6.5.14 (
||
)一元算术运算符
!
的语义在 §6.5.3.3/4 结束:结果类型全部为
int
,可能的值为0
和1
。 (除非我错过了一些。)In C99 §6.5.8 Relational Operators, item 6 (
<
,>
,<=
and>=
):As for equality operators, it's a bit further in §6.5.9 (
==
and!=
):The logical AND and logical OR are yet a bit further in §6.5.13 (
&&
)... and §6.5.14 (
||
)And the semantics of the unary arithmetic operator
!
are over at §6.5.3.3/4:Result type is
int
across the board, with0
and1
as possible values. (Unless I missed some.)C 的布尔运算符遵循 Postel 法则:在你所做的事情上保持保守,自由地接受别人的东西。它将布尔表达式中的任何非零值视为 true,但它本身始终会生成 0 或 1。
2 != 3
始终为1
。C follows Postel's Law for its boolean operators: be conservative in what you do, be liberal in what you accept from others. It will treat any non-zero value as true in boolean expressions, but it will always produce either a 0 or a 1 itself.
2 != 3
is always1
.来自 ISO C99 标准,第 6.5.8 节:
来自第 6.5.9 节:
逻辑合取 (
&&
) 和析取 (||
) 运算符也会发生同样的情况。PS:顺便说一句,这就是为什么按位运算符(
&
和|
)通常可以用作逻辑运算符的非短路版本。From the ISO C99 standard, section 6.5.8:
From section 6.5.9:
Same thing happens with the logical conjunction (
&&
) and disjunction (||
) operators.PS: Incidentally, this is why the bitwise operators (
&
and|
) can usually be used as non-short-circuiting versions of the logical operators.所有产生逻辑真/假值的 C 运算符始终会产生
int
类型的结果,其中 false 值为0
,1< /code> 为真。
并非所有产生逻辑真/假值的 C表达式都是这种情况。例如,
中声明的is*()
字符分类函数 (isdigit()
,isupper( )
等)如果条件为 false,则返回0
,但如果条件为 true,则可能返回任何非零值。只要您直接使用结果作为条件:
并且不要尝试将其与某些内容进行比较:
这不会导致任何问题。
(您可以安全地将结果与
0
或false
进行比较,但没有充分的理由这样做;这就是!< /code> 运算符用于。)
All C operators that yield logically true/false values always yield a result of type
int
with the value0
for false,1
for true.That's not the case for all C expressions that yield logically true/false values. For example, the
is*()
character classification functions declared in<ctype.h>
(isdigit()
,isupper()
, etc.) return0
if the condition is false, but may return any non-zero value if the condition is true.As long as you use the result directly as a condition:
and don't attempt to compare it to something:
this shouldn't cause any problems.
(You can safely compare the result to
0
orfalse
, but there's no good reason to do so; that's what the!
operator is for.)