I stumbled over a curious problem with BOOL
return type in blocks. Having the following definition:
typedef BOOL (^BoolBlock)(void);
…this code passes:
BoolBlock foo = ^{ return YES; };
…but this fails to compile:
BoolBlock bar = ^{ return YES || NO; };
With the following error message:
Incompatible block pointer types initializing 'BoolBlock' (aka 'BOOL (^)(void)') with an expression of type 'int (^)(void)'
I can solve the issue using an explicit cast, but shouldn’t this work without it? Is there a better solution?
|| operator returns int type as Chuck said.
BoolBlock bar = ^{ return (BOOL)(YES || NO); };
or
BoolBlock bar = ^BOOL (void){ return YES || NO; }; BoolBlock bar = ^BOOL (){ return YES || NO; }; // warns in gcc, ok with clang
You're probably thinking the ||
operator works in languages like Ruby and Python, where it returns in the first operand that is truthy. In C, it returns 1 if either operand is truthy and 0 otherwise — that's why it thinks you're returning an integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With