Cast pointer that isn't nil to BOOL returns NO
I've recently encountered 开发者_如何学编程a very rarely reproducible bug. If I cast a pointer that isn't nil to BOOL for some reason I get NO!!!11 I know that BOOL is typedef of signed char. Can that be a problem?
If the pointer is of the form 0xNNNNNN00
or (on 64-bit) 0xNNNNNNNNNNNNNN00
, where N
is any hex digit, then a cast to BOOL
(an unsigned char
) will leave you with 0
since it will truncate all the non-zero bits.
To properly convert a pointer to BOOL
, use the inequality operator:
BOOL isNotNull = (myPointer != NULL);
Its because a pointer is 32 bit large and a char is just 8 bits. So when converting from a pointer to a char, it will trim 24 bits. So the possibility that the remaining 8 bits are just zeros is pretty high especially when the pointers address is high.
What you can do is the following:
BOOL myBool = (myPointer != NULL); // This will evaluate if the pointer is true (>0) or false (NULL)
BOOL
is not a type that should be used, for this exact reason. In fact I can think of little use for a boolean-type variable (as opposed to just using the original value, pointer or whatever, on which it's based) except in the case of giant bit arrays where you'd need special code to address bits. If you really want a boolean type, use C99 _Bool
(or bool
in stdbool.h
) which has the correct conversion semantics rather than modulo-256 reduction.
精彩评论