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?
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.