本文介绍了有YES / NO之间的差异,TRUE / ​​FALSE和真/假在Objective-C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题真的;有这些值之间的差(和有BOOL和布尔之间的差)?一位同事提到,他们评估在Objective-C的不同的事情,但是当我看着的typedef在各自的.h文件,YES / TRUE /真正的都被定义为 1 和NO / 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 变量布尔值。 ç流程的基础上,他们是否计算为0或布尔前pressions不是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) { ... }

这就是为什么你可以评估的任何基本类型或前pression为布尔测试(包括,例如指针)。需要注意的是你应该做前者,而不是后者。

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 可能被分配一个非零值,这是不肯定的,但是,在我认为更重要的是,它没有前preSS的意图正确:

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.

这篇关于有YES / NO之间的差异,TRUE / ​​FALSE和真/假在Objective-C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 03:35