且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在objective-c中YES/NO,TRUE/FALSE和true/false之间有区别吗?

更新时间:2022-06-13 02:32:30

没有实际区别提供你使用 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.