I found some code similar to the following:
BOOL hasValue_:1;
- (BOOL) hasValue {
return !!hasValue_;
}
- (void) setHasValue:(BOOL) value {
hasValue_ = !!value;
}
I’m wondering why the double exclamation points are necessary? Are we not already passing BOOL to the method and returning BOOL? Is BOOL really a typedef for an int?
Thanks!
EDIT
Thanks for all of the responses thus far. I understand that using !! with other data types effectively performs some typecasting to a boolean result. However, in the example above, I’m strictly working with BOOL already.
EDIT
If I’m working with a BOOL already, why is it necessary to normalize it to a 0 for false and 1 for true? Doesn’t a BOOL guarantee that it is false for 0 and true for everything else?
BOOLis asigned char, or acharposing as a boolean type viatypedef. It will happily represent any integer in the range[SCHAR_MIN...SCHAR_MAX]. The double exclamation point applies a boolean NOT operation twice, which effectively converts the original value to an int of 0 or 1, narrowing the value to the range of boolean.But there’s a twist:
BOOL hasValue_:1;declares a single-bit bitfield representation. It can represent two values.return !!hasValue_;is not needed. However, it is needed to correctly narrow when going fromsigned char(BOOL) to one bit.Nope. It’s a
signed char.!!valuereduces input values toYESorNO.BOOLis asigned char. Atypedefofsigned chardoes not make this guarantee.C99 (which has been available for you to use for many years when targeting osx or ios) has a more useful boolean type representation (
bool). Unfortunately,BOOLremains in regular use in objc for historical reasons. Personally, I useBOOLonly when necessary (e.g. overriding).