Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: ObjC BOOL and boolean c expressions



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:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden
References: 
 >Re: ObjC BOOL and boolean c expressions (From: Scott Ribe <email@hidden>)
 >Re: ObjC BOOL and boolean c expressions (From: glenn andreas <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.