Objective-c 中的 YES/NO,TRUE/FALSE 和 true/false 之间有区别吗? [英] Is there a difference between YES/NO,TRUE/FALSE and true/false in objective-c?
问题描述
真的很简单的问题;这些值之间是否存在差异(BOOL 和 bool 之间是否存在差异)?一位同事提到他们在 Objective-C 中评估不同的东西,但是当我查看他们各自的 .h 文件中的 typedef 时,YES/TRUE/true 都被定义为 1
和 NO/FALSE/false 都定义为 0
.真的有区别吗?
Simple question really; is there a difference between these values (and is there a difference between BOOL and bool)? A co-worker mentioned that they evaluate to different things in Objective-C, but when I looked at the typedefs in their respective .h files, YES/TRUE/true were all defined as 1
and NO/FALSE/false were all defined as 0
. Is there really any difference?
推荐答案
没有实际区别 provided 你使用 BOOL
变量作为布尔值.C 根据布尔表达式的计算结果是否为 0 来处理它们.所以:
There is no practical difference provided you use BOOL
variables as booleans. C processes boolean expressions based on whether they evaluate to 0 or not 0. So:
if(someVar ) { ... }
if(!someVar) { ... }
意思相同
if(someVar!=0) { ... }
if(someVar==0) { ... }
这就是为什么您可以将任何原始类型或表达式评估为布尔测试(包括例如指针)的原因.注意你应该做前者,而不是后者.
which is why you can evaluate any primitive type or expression as a boolean test (including, e.g. pointers). Note that you should do the former, not the latter.
请注意,如果您将钝值分配给所谓的 BOOL
变量并测试特定值,则 会有所不同,因此总是将它们用作布尔值,并且仅从它们的 #define
值中分配它们.
Note that there is a difference if you assign obtuse values to a so-called BOOL
variable and test for specific values, so always use them as booleans and only assign them from their #define
values.
重要的是,永远不要使用字符比较来测试布尔值——这不仅有风险,因为 someVar
可能被分配一个非零值,这不是 YES,但在我看来,更重要的是,它失败了正确表达意图:
Importantly, never test booleans using a character comparison -- it's not only risky because someVar
could be assigned a non-zero value which is not YES, but, in my opinion more importantly, it fails to express the intent correctly:
if(someVar==YES) { ... } // don't do this!
if(someVar==NO ) { ... } // don't do this either!
换句话说,按照预期使用和记录在案的方式使用构造,您将避免在 C 语言中受到伤害.
In other words, use constructs as they are intended and documented to be used and you'll spare yourself from a world of hurt in C.
这篇关于Objective-c 中的 YES/NO,TRUE/FALSE 和 true/false 之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!