问题描述
真的很简单的问题;这些值之间是否存在差异(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?
推荐答案
没有实际区别提供你使用 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之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)