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



On Sep 5, 2007, at 8:24 PM, glenn andreas wrote:


On Sep 5, 2007, at 10:03 PM, Scott Ribe wrote:

However Objective-C BOOL, as pointed out before, is just a typedef
for a char, and YES & NO are just typedefs, so there is no coercion, so:


 BOOL foo = 42;
 if( foo == YES )

Would not take the branch.

Of course there is no need to ever write "if( foo == YES )", so it's an easy
problem to avoid--just learn that a variable of type bool/BOOL is an
expression of type bool/BOOL and thus does not need to be compared to a
bool/BOOL value in order to yield a bool/BOOL result.


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.

Wow, that's tricky. Does this generate a compiler warning? I would hope so, but you never know…


OTOH, either:

if ([theEvent modifierFlags] & NSShiftKeyMask) {
	// this works
}

BOOL isShift = ([theEvent modifierFlags] & NSShiftKeyMask) != NSShiftKeyMask; // explicitly test to see if that bit is set
if (isShift) {
// works as well
}

And option #3, for an ObjC++ programmer, would be to use the "bool" type instead of BOOL.



_______________________________________________

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.