• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: ObjC BOOL and boolean c expressions
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: ObjC BOOL and boolean c expressions


  • Subject: Re: ObjC BOOL and boolean c expressions
  • From: John Stiles <email@hidden>
  • Date: Wed, 5 Sep 2007 20:32:52 -0700

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:
This email sent to email@hidden


  • Follow-Ups:
    • Re: ObjC BOOL and boolean c expressions
      • From: "Clark Cox" <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>)

  • Prev by Date: Re: ObjC BOOL and boolean c expressions
  • Next by Date: *** JUNK MAIL ***Intercepting application start?
  • Previous by thread: Re: ObjC BOOL and boolean c expressions
  • Next by thread: Re: ObjC BOOL and boolean c expressions
  • Index(es):
    • Date
    • Thread