Re: !foo vs foo == nil
Re: !foo vs foo == nil
- Subject: Re: !foo vs foo == nil
- From: "Michael Ash" <email@hidden>
- Date: Thu, 21 Aug 2008 10:15:27 -0400
On Thu, Aug 21, 2008 at 6:47 AM, Negm-Awad Amin <email@hidden> wrote:
>
> Am Do,21.08.2008 um 12:25 schrieb Thomas Engelmeier:
>
>>
>> Am 21.08.2008 um 11:04 schrieb Negm-Awad Amin:
>>
>>> Sometimes you see in source code something like this:
>>> if( booleanVarOrExpression == YES )
>>> (I think, Rentzsch does it that way, IIRC) and Ithink, that this is
>>> simply correct.
>>
>> Oh, that is another discussion.
>
> Yeah, but connected
>
> It is antoher discussion in that way, that we have other types. (BOOL vs.
> type of logical expression in C)
> It is the same discussion in that way, that most programmers make some
> assumptions about the value (and the casting).
>
> (I bet, that 10 % believe, that the expression inside the if is typed BOOL)
I'd be very surprised at this, given that BOOL is found only in
Objective-C, and if statements are found in C.
> Doing this is absolutly correct.
> BOOL var = …; // Something evaluating to YES or NO
> if( var == YES )
It's "correct" in that it is a legal language construct and it has
well-defined results. But it is incorrect as far as doing what most
people would want it to do. Consider this:
BOOL var = 2;
if(var == YES)
That if statement will evaluate to false, even though the value of
"var" is conceptually true. ("True" in C meaning anything that is not
zero.) For this reason, I recommend never comparing with YES. If you
are mentally unable to simply write "if(var)", then I recommend using
"if(var != NO)". I consider any code that compares against YES as you
wrote to have a bug.
> a simple
>
> BOOL var = …; // Something evaluating to YES or NO
> if( var )
>
> is a very good hidden implicit cast from BOOL to logical expression.
There is no "hidden implicit cast". The if statement simply checks its
contents for truth or falseness, which is to say that it checks it for
zero or non-zero.
> However I use the simple condition (without == YES), too – for convenience.
Your code then has a bug, in my opinion, and this is likely to
manifest in ways extremely annoying and difficult to diagnose.
> BTW: This is an implicit cast, too:
>
> BOOL var = a && b;
>
> because the result of the right expression types to logical expression, not
> to BOOL.
No, the right side of the expression is typed *int*. There is no such
C type as "logical expression".
I recommend you learn more about the C language before you continue
any further, because you have a lot of misconceptions and many of them
are going to cause you to write bad code.
Mike
_______________________________________________
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