• 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: !foo vs foo == nil
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: !foo vs foo == nil


  • Subject: Re: !foo vs foo == nil
  • From: James Montgomerie <email@hidden>
  • Date: Thu, 21 Aug 2008 11:27:28 +0100

On 21 Aug 2008, at 09:06, Clark Cox wrote:
This is not a "hack" or a "coincidence", this is by design. A non-NULL
pointer *is* a boolean expression that evaluates to true, just as a
non-zero integer is. Again, it doesn't work by coincidence, it is a
guarantee of the language standard.

To go off on a bit of a tangent, if you read this without thinking of all the implications of other parts of the language you /can/ still run into problems. For example:


BOOL b = (BOOL)v;

could leave you with b == NO even if v != 0.

If BOOL is a shorter type than value's type (e.g. if BOOL is char and v is long), and if the lower bits of v are all 0 but the higher bits are not, the higher bits will just get truncated off in the conversion.

i.e. this:

---

#include <Foundation/Foundation.h>

int main() {
    int myFlags = 0x01000200;
    int myBitMask = 0x01000000;

BOOL isFlagSet = (BOOL)(myFlags & myBitMask);
if(isFlagSet == NO) { // Could (of course) use "if(!isMasked)" here, I just used this for clarity
printf("Oh No!\n");
}
return 1;
}


---

gives:

---

Thing:tmp jamie$ gcc test.m -framework Foundation
Thing:tmp jamie$ ./a.out
Oh No!

---

This has puzzled me for a while in the past when I was wondering why my bit masks were not evaluating correctly.

Jamie.

_______________________________________________

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


References: 
 >!foo vs foo == nil (From: Torsten Curdt <email@hidden>)
 >Re: !foo vs foo == nil (From: Filip van der Meeren <email@hidden>)
 >Re: !foo vs foo == nil (From: Torsten Curdt <email@hidden>)
 >Re: !foo vs foo == nil (From: "John C. Randolph" <email@hidden>)
 >Re: !foo vs foo == nil (From: Jules Colding <email@hidden>)
 >Re: !foo vs foo == nil (From: Thomas Davie <email@hidden>)
 >Re: !foo vs foo == nil (From: "Clark Cox" <email@hidden>)

  • Prev by Date: Re: !foo vs foo == nil
  • Next by Date: Re: !foo vs foo == nil
  • Previous by thread: Re: !foo vs foo == nil
  • Next by thread: Re: !foo vs foo == nil
  • Index(es):
    • Date
    • Thread