Is there a difference between YES/NO,TRUE/FALSE and true/false in objective-c?
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!\n");
}
if (b != YES) {
printf("b is not YES!\n");
}
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
.
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) { ... }
means the same as
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.
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.
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!
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.