Re: ObjC BOOL and boolean c expressions
Re: ObjC BOOL and boolean c expressions
- Subject: Re: ObjC BOOL and boolean c expressions
- From: "Clark Cox" <email@hidden>
- Date: Fri, 31 Aug 2007 11:07:58 -0700
On 8/30/07, Eyal Redler <email@hidden> wrote:
> Hi,
>
> I'm not sure where and when but I recall reading something about ObjC
> BOOL type values YES and NO not being the same as whet a boolean
> expression might produce.
> I can't recall the exact details but there was some kind of gotcha
> related to this. For example, the expression
>
> BOOL myBool=(myInt==1);
>
> might set myBool differently then
>
> BOOL myBool=(myInt==1)?YES:NO;
No, the two are identical.
> Or maybe it was that
>
> if (myBool)
> [foo bar];
>
> will perform differently then
> if (myBool==YES)
> [foo bar];
This can behave differently (because BOOL is a typedef for char, and
can therefore hold values other than 1 or 0). For example:
BOOL myBool = 2;
if(myBool==YES)
[foo bar];
though I'd advise against setting a BOOL to anything other than YES or NO.
> Or maybe it was just that if I do this
>
> int myInt=4096;
> BOOL myBool=myInt;
>
> Then if (myBool) will evaluate to false.
In this case, it is undefined what myBool will evaluate to (unless
you're on an odd system with char's that are greater than 13 bits).
One way to ensure that integers are converted properly to boolean
values is to prefix them with "!!", as in:
int myInt=4096;
BOOL myBool=!!myInt;
At this point, myBool is guaranteed to be equal to 1.
> This issue was bugging me for quite some time and I'm wondering if
> somebody recalls this discussion.
The general rule: Never compare directly to YES
--
Clark S. Cox III
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