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:
- Does this imply that
boolbe preferred toBOOL? Why or why not? - Is it okay to use
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)4096being evaluated to0is a simple arithmetic overflow, just as(BOOL)256, sinceBOOLis anunsigned char. And I think that the!!casting trick (“double negation”) works fine:That means I’d use
BOOLto keep the standard Cocoa coding style and simply watch for dangerous type casts. ThethatBool ? YES : NOexpression hurts my eyes, why would you want to do that? 🙂