Re: ObjC BOOL and boolean c expressions
Re: ObjC BOOL and boolean c expressions
- Subject: Re: ObjC BOOL and boolean c expressions
- From: Wincent Colaiuta <email@hidden>
- Date: Thu, 6 Sep 2007 12:47:50 +0200
El 6/9/2007, a las 5:24, glenn andreas escribió:
But a similar "gotcha" case is:
BOOL isShift = [theEvent modifierFlags] & NSShiftKeyMask;
if (isShift) {
// this will never be hit, regardless of the state of the shift key!
}
This is because the result of the expression tests a single bit
that happens to be higher than will fit in the BOOL, resulting in
isShift always being 0.
I was once bitten by a similar bug when I foolishly wrote the
following, thinking that the explicit cast was making my intentions
clearer:
(BOOL)(foo & bar)
but when the value had only high-order bits set and was cast to BOOL
it became 0 (NO). Although writing this without the cast would have
worked:
(foo & bar)
I preferred to explicitly "normalize" the result:
!!(foo & bar)
Note that you can fall into the same trap even when the explicit cast
isn't right there in front of your eyes:
- (BOOL)test
{
return foo & bar;
}
In the method there is an implicit cast (the return of type BOOL)
that can yield the same bug for appropriate values of foo and bar.
This would be better:
- (BOOL)test
{
return !!(foo & bar);
}
I wrote a short article about this on my weblog when I first ran into
it:
<http://wincent.com/a/about/wincent/weblog/archives/2007/05/
clever_boolean.php>
Probably something every programmar runs into once in their career
and then never makes the same silly mistake again, hopefully. You
gotta love C. Hehe.
Cheers,
Wincent
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden