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: Howard Moon <email@hidden>
- Date: Fri, 24 Feb 2012 09:23:33 -0800
Really, this belongs in the Objective-C mailing list, but...
If the language provides a feature, then it is "correct" in terms of the language.
That said, I always use the long form, just to be sure I'm always specifying a boolean condition. This helps me when I'm combining or separating multiple conditions or simply trying to read my code later. I'm a big believer in using parentheses around sub-conditions as well, and never simply relying on order of evaluation.
I know there are many (esp. C programmers) who prefer the most abbreviated format possible, but I go the opposite way, always wanting to be able to easily read what I've written. After all, the symbols themselves will go away once compiled, and the extra time and space for the characters is inconsequential (these days) when compared to the need to easily identify what the heck you've written! :-)
-Howard
On Feb 24, 2012, at 6:50 AM, Oleg Krupnov wrote:
> An interesting question. The following samples are equivalent in terms
> of compiled code, but which one is more correct from the language's
> point of view?
>
> self = [super init];
> if (self)
> {
> }
> return self;
>
> self = [super init];
> if (self != nil)
> {
> }
> return self;
>
> The Xcode samples promote the first variant, but I'm wondering if the
> second one is more correct?
>
> The "nil" is defined as follows (jumped to definition)
>
> #define nil NULL
> #define NULL ((void*)0)
>
> So basically, nil is of type "void*", so the expression "self != nil"
> compares two pointers and the result is "boolean", which is perfect
> for testing in the "if" statement. But the "self" alone is of type
> "pointer" and so when it is tested by the "if" statement, it's
> implicitly cast to the type "boolean".
>
> I also heard that generally speaking NULL is not necessarily always
> equal to 0 on all architectures.
>
> Thoughts?
> _______________________________________________
_______________________________________________
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