问题
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
bool
be 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.
回答1:
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? :)
回答2:
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) {
}
回答3:
When using an int, you can always be explicit when setting a BOOL by checking if the int is equal to a particular value, e.g.
BOOL yesNo = ((int)4096 > 0);
BOOL enableButton = (someInt >= 16);
In other words, don't pass the int to the BOOL directly; turn it into a true/false statement.
来源:https://stackoverflow.com/questions/9433121/implications-of-int-values-not-fitting-bool-or-bool-for-objective-c