Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

boolean - Is there a difference between YES/NO,TRUE/FALSE and true/false in objective-c?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe there is a difference between bool and BOOL, check out this webpage for an explanation of why:
http://iosdevelopertips.com/objective-c/of-bool-and-yes.html

Because BOOL is an unsigned char rather than a primitive type, variables of type BOOL can contain values other than YES and NO.

Consider this code:

BOOL b = 42;

if (b) {
    printf("b is not NO!
");
}

if (b != YES) {
    printf("b is not YES!
");
}

The output is:

b is not NO!
b is not YES!

For most people this is an unnecessary concern, but if you really want a boolean it is better to use a bool. I should add: the iOS SDK generally uses BOOL on its interface definitions, so that is an argument to stick with BOOL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...