In the comments here -- https://stackoverflow.com/a/9393138/8047 -- I discovered that BOOL
has some unexpected behavior when setting its value from an int
value. Mostly, if the value is set to 0x1000
it gets evaluated as FALSE
(surprisingly).
NSLog(@"All zero? %d %d", (BOOL)0, (bool)0);
NSLog(@"All one? %d %d %d", (BOOL)4095, (BOOL)4096, (BOOL)4097); // 4096=0x1000 or 8-bits
NSLog(@"All one? %d %d %d", (bool)4095, (bool)4096, (bool)4097);
Produces:
All zero? 0 0
All one? -1 0 1
All one? 1 1 1
I think this is odd, but then again, I don't cast from int
to BOOL
much anyway. However:
bool
be preferred to BOOL
? Why or why not?if (thatBool) {
or should one prefer
if (thatBool ? YES : NO) {
And why?
Note: This is a more specific version of this question of this -- Objective-C : BOOL vs bool -- but I think it adds to it and is not a duplicate.
I think that (BOOL)4096
being evaluated to 0
is a simple arithmetic overflow, just as (BOOL)256
, since BOOL
is an unsigned char
. And I think that the !!
casting trick ("double negation") works fine:
NSLog(@"%i", (BOOL)256); // 0
NSLog(@"%i", !!256); // 1
That means I’d use BOOL
to keep the standard Cocoa coding style and simply watch for dangerous type casts. The thatBool ? YES : NO
expression hurts my eyes, why would you want to do that? :)
1) bool
is the C++ type, BOOL
is the Objective-C one.
Casting from int
to BOOL
doesn't work properly because YES
is just (BOOL)1
= (signed char)1
(= 0x001) and that isn't equal to (signed char)4
(= 0x100), for example.
2) Both will work, the second might be unreadable to somebody with little experience in programming. I prefer the good old c-style safe condition check with the constant on the left to prevent accidental omission of one of the equal signs.
if (YES == isEnabled) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With