Re: Block variable syntax related question
Re: Block variable syntax related question
- Subject: Re: Block variable syntax related question
- From: Bavarious <email@hidden>
- Date: Fri, 09 Sep 2011 16:38:32 -0300
(not sure whether xcode-users is the appropriate place for this question)
On 9 Sep 2011, at 14:56, David Hoerl wrote:
> I had an issue (rdar://10100914) where the compiler did not properly determine the return type, forcing me to use a local variable:
>
> typedef BOOL (^tester)(id obj, NSUInteger idx, BOOL *stop);
>
> tester finder = ^(id obj, NSUInteger idx, BOOL *stop) { return ret = [obj compare:@"foo"] == 0 ? YES : NO; };
>
> error: incompatible block pointer types initializing 'tester' (aka 'BOOL (^)(id, NSUInteger, BOOL *)')
>
> with an expression of type
> 'int (^) id, NSUInteger, BOOL *)'
In this particular case, the conditional operator promotes the second and third operands to int as specified in the C99 standard. This means that
[obj compare:@"foo"] == 0 ? YES : NO
is an int expression, not a BOOL one. The block variable has return type BOOL and the block literal has inferred return type int, hence the compiler error.
You could cast the expression above to BOOL. Replace:
[obj compare:@"foo"] == 0 ? YES : NO
with
(BOOL)([obj compare:@"foo"] == 0 ? YES : NO)
e.g.:
tester finder = ^(id obj, NSUInteger idx, BOOL *stop){ return (BOOL)([obj compare:@"foo"] == 0 ? YES : NO); };
so that the inferred return type is also BOOL.
> [BTW, this worked: :
> tester finder = ^(id obj, NSUInteger idx, BOOL *stop) { BOOL ret = [obj compare:@"foo"] == 0 ? YES : NO; return ret; };]
In this case the block variable has return type BOOL and the block literal has inferred return type BOOL because ret is BOOL; no problems there.
> I tried various ways to add the return type to the declaration, eg
>
> tester finder = BOOL (^)(id obj, NSUInteger idx, BOOL *stop) { BOOL ret = [obj compare:@"foo"] == 0 ? YES : NO; return ret; };
>
> but could never get anything to compile. Is there a way to add the return type above? I am guessing no as I have not found any such examples, but figured I'd ask just in case…
The correct syntax for a block literal is ^return-type… but you’ve used return-type (^)… instead. The following compiles with no errors:
tester finder = ^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj compare:@"foo"] == 0 ? YES : NO; };
-- Bavarious _______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden