Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with BOOL return type in Objective-C blocks

Tags:

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?

like image 496
zoul Avatar asked May 09 '11 08:05

zoul


2 Answers

|| 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 
like image 84
Kazuki Sakamoto Avatar answered Sep 17 '22 17:09

Kazuki Sakamoto


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.

like image 41
Chuck Avatar answered Sep 19 '22 17:09

Chuck