Re: [Obj-C] if (self) vs. if (self != nil)
Re: [Obj-C] if (self) vs. if (self != nil)
- Subject: Re: [Obj-C] if (self) vs. if (self != nil)
- From: Scott Ribe <email@hidden>
- Date: Fri, 24 Feb 2012 10:52:17 -0700
On Feb 24, 2012, at 7:50 AM, Oleg Krupnov wrote:
> I also heard that generally speaking NULL is not necessarily always
> equal to 0 on all architectures.
>
> Thoughts?
Yeah, don't worry about it. The if(self) form is idiomatic C, by which I mean it's the way that C code has been written since the dawn of time, not that it's quirky. The if(self != nil) is perfectly correct as well, but adds nothing except satisfying some people's personal preference--the only people I've ever seen argue strongly in favor of it are ones who learned Pascal before C...
Yes, the underlying value of the NULL pointer may not be 0 on some architectures, but the language guarantees that if(self) will evaluate as you expect if self is the null pointer (and that assigning constant 0 to a pointer will set it to the null pointer). The few people who argue that if(self) is not portable are simply wrong.
Now there is one style that is worth defending, which is when comparing a variable to a constant, put the constant first. Consider the following:
if(self == nil)...
if(self = nil)...
if(nil == self)...
if(nil = self)...
The 1st & 3rd are the correct conditions, the 2nd & 4th are typos. But the 2nd compiles and gives incorrect behavior, while the 4th fails to compile.
Of course if(self) is not subject to that kind of typo, but if you're going to insist on the verbose version, you might as well use if(nil == self).
--
Scott Ribe
email@hidden
http://www.elevated-dev.com/
(303) 722-0567 voice
_______________________________________________
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