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

2023-10-05移动开发问题
17

本文介绍了在objective-c中YES/NO,TRUE/FALSE和true/false之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

如何将 32 位 PNG 转换为 RGB565?
How to convert 32 bit PNG to RGB565?(如何将 32 位 PNG 转换为 RGB565?)...
2024-08-12 移动开发问题
21

正确的 cocos2d 场景重启?
Proper cocos2d scene restart?(正确的 cocos2d 场景重启?)...
2024-08-12 移动开发问题
7

游戏中心 facebook 喜欢
Game center facebook like(游戏中心 facebook 喜欢)...
2024-08-12 移动开发问题
3

从 Documents 目录存储和读取文件 iOS 5
Storing and reading files from Documents directory iOS 5(从 Documents 目录存储和读取文件 iOS 5)...
2024-08-12 移动开发问题
9