On 24 Feb 2012, at 8: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?
It's a matter of style; neither is "more correct." C has always guaranteed that in source (if not necessarily in the target architecture), NULL pointers can be treated as 0. if (self) and if (self != nil) should produce identical code. Some people find the second easier to read. I find the first to be so fundamental an idiom that anyone who can't understand it has no business working with C. > 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". C, earlier than C99, has no concept of a Boolean. Conditionals are not false or true, but zero (or NULL) or non-zero. C99 has a bool (_Bool) type, but has to conform to the 0/non-0 rule. Boolean operators reduce true expressions to 1, but code that relies on 1 (or true, or YES) being the only non-false value is incorrect. — F _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) 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: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com