我遇到了一篇文章,其中提到 !0 的结果取决于编译器。结果可以是 1 或 FF 或 FFFF 等等。
至于 C99 标准 6.5.3.3 一元算术运算符,
逻辑否定运算符的结果!如果其操作数的值比较不等于 0,则为 0,如果其操作数的值比较等于 0,则为 1。结果的类型为 int。表达式 !E 等价于 (0==E)。
它真的依赖于编译器吗?
您似乎已经回答了您自己的问题,引用了标准,其中指定结果必须为 0 或 1。
因此,我能猜到的只是你在问是否所有 C 编译器在这方面都符合标准。由于我没有使用过所有编写过的 C 编译器,因此我无法真正明确地回答这个问题。不过,我从未使用过或听说过产生任何其他价值的东西——考虑到我在这里、在 Usenet 等上待了这么多年,似乎如果存在这样的野兽,我可能已经听说过其中。
编辑:可能值得注意的是,即使在 K&R1 中,它也被特别描述为产生 0 或 1(§A.7.2):
逻辑否定运算符的结果!如果其操作数的值为 0,则为 1,如果其操作数的值非零,则为 0。
Each compiler should have in their description a list of standards they follow. Of course this description is not always totally true (some compiler contains bug or misinterpretation of the standards), but that behaviour with boolean is so simple and so old (comes from first day of C) that I would be really surprised if a new compiler behave differently.
So I always got it as a official standard and also a de-facto standard: (!0) = 1
and (!1) = 0
, both of type int.
Be careful however that in C++ boolean operators returns a bool
value, so if you compile in C++, bool will be used, not int. However bool and int are directly interchangeable, except the fact that some C++ compiler will warn you if you do something strange, like bool x = 10;
.