Re: !foo vs foo == nil
Re: !foo vs foo == nil
- Subject: Re: !foo vs foo == nil
- From: "Clark Cox" <email@hidden>
- Date: Thu, 21 Aug 2008 01:06:11 -0700
On Thu, Aug 21, 2008 at 12:21 AM, Thomas Davie <email@hidden> wrote:
>
> On 21 Aug 2008, at 09:06, Jules Colding wrote:
>
>>
>> On 21/08/2008, at 01.56, John C. Randolph wrote:
>>
>>>
>>> On Aug 20, 2008, at 4:15 PM, Torsten Curdt wrote:
>>>>
>>>> There was a common perception that NULL is not really the same as nil.
>>>> But seems like in the end it really is (void*)0.
>>>
>>>
>>> They differ in type, not in value.
>>>
>>> "NULL" is (void *) 0.
>>> "nil" is (id) 0.
>>> "Nil" is (Class) 0.
>>>
>>> Personally, I prefer "if (!foo)" over "if (foo == nil)", because the
>>> latter has the hazard of a typo that compiles. You can lose a fair bit of
>>> time staring at "if (foo = nil)" before you spot the mistake.
>>
>> Which is why you should always write "if (nil == foo)".
>
> Just to add my 2 cents to this discussion, I think there's something which
> hasn't been brought up (and I guess isn't often brought up by C
> programmers).
>
> One of the two options doesn't make sense here.
It may not make sense to those who aren't used to C (or, more
accurately, are *more* used to another language), but it makes perfect
sense to C programmers (just as [foo method: bar] doesn't make sense
to C programmers, but makes perfect sense to Obj-C programmers).
Different languages have different idioms. C programmers likely tend
not to bring it up, because it is second nature to them.
> Because of C's weak type system ! works on almost anything you throw at it.
> However, it is a *boolean* operator. Boolean negating a pointer is a hack
> that by happy coincidence works.
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.
Note, that the same is true in C++, which has a much stronger type
system than C.
> On the other hand, nil == foo is type
> safe, and makes semantic sense.
>
> For that simple reason, I'd go for nil == foo every time.
--
Clark S. Cox III
email@hidden
_______________________________________________
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