Reputation: 479
Let's say I have a pointer to some object, called myObject
, and I need to know, whether it is really pointing to something. How can this code:
// assume MyObjectClass *myObject;
return (BOOL)myObject;
return 112? I know, that I can always write
return (myObject == nil);
and everything will be fine. But until today I have always assumed, that explicit casting of anything to bool will always return true
or false
(as far as I know, 0 is always considered as false
and any other value as true
) and that BOOL with it's YES
and NO
values is just "renamed" bool. So basically, my questions are:
Upvotes: 2
Views: 980
Reputation: 5925
In Objective-C, the BOOL
macro is just a typedef
for signed char
with YES
/NO
defined, but bool
is an actual boolean, which can be true
or false
.
It returns 112, because it rounds the address of your pointer to signed char
type.
Here is some discussion with good answers:
Objective-C : BOOL vs bool
Is there a difference between YES/NO,TRUE/FALSE and true/false in objective-c?
Upvotes: 4
Reputation: 145829
In C , bool
is a stdbool.h
macro for boolean type _Bool
.
And a conversion of a non-zero integer value to _Bool
is guaranteed to yield 1
.
That is, the result of 1 == (bool) 42
is 1
.
If you are using a BOOL
type as an alias for another integer type (like signed char
), you can get a different result:
The result of 1 == (BOOL) 42
is 0
.
Upvotes: 1
Reputation: 28302
The definition of "true" in C is any non-zero number. Therefore 112 would be considered true as far as C is concerned. From the C99 standard:
6.3.1.2 Boolean type
When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
Your value is not converted to 1 because you are converting to BOOL not _Bool. The conversion to 0/1 will be technically handled inside the if (though in reality the implementation is more likely to be (myObject != 0) inside any if/while type statement).
Upvotes: 1