Re: Equivalent ?
Re: Equivalent ?
- Subject: Re: Equivalent ?
- From: Adam Leonard <email@hidden>
- Date: Sun, 18 Jan 2009 02:12:37 -0500
Technically, they are not equivalent. The BOOL type is not a native
boolean type in C. If you command double click on it in XCode, you can
see that it is a signed char, meaning it can store any value from -128
to +127. This differs from a native boolean type, such as the
(lowercase) bool in C99, in that these types usually only store 0 or 1.
If you command double click on YES, you will see that it is defined as
a BOOL with value 1. The problem is that in C, *any* nonzero value
(not just 1) is considered to be true if treated as a boolean.
So, in your first example, you are explicitly comparing a BOOL to 1.
It would, however, be correct if isMemberOfClass decided to return 42
or something to mean true. In this case, your first example would fail
(42 != 1).
Your second example will evaluate to true if the value stored in the
BOOL is *any* nonzero value (that's just how comparison works in C),
so if isMemberOfClass returns 42, your code will still work (42 != 0)
Thus, it is best to use YES only with assignments, and never with
comparisons.
In my opinion this is quite unfortunate, as having no comparison
operator in an if statement hurts readability.
Sometimes, doing the following makes code a bit more readable:
if ([foo didSomethingWork] != NO) ...
since the only value interpreted as false is 0, and NO is always
equivalent to 0.
Adam Leonard
On Jan 18, 2009, at 12:54AM, Michael wrote:
Hi all,
I am curious as to whether the following expressions are equal?
Given class "Square" and an instance of Square (mySquare).
>>>>>>>>>>>>>>>>>>>
if ( [mySquare isMemberOfClass: [Square class]] ==YES)
NSLog(@" mySquare is a member of Class Square");
vs
if ( [mySquare isMemberOfClass: [Square class]])
NSLog(@" mySquare is a member of Class Square");
<<<<<<<<<<<<<<<<<
I would have thought the comparison to "YES" is redundant? Or is it
regarded as poor programming to omit the "==YES".
Thanks
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Objc-language mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to 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