Re: Stupid newbie question - determine if integer is even or odd
Re: Stupid newbie question - determine if integer is even or odd
- Subject: Re: Stupid newbie question - determine if integer is even or odd
- From: Andrew Demkin <email@hidden>
- Date: Tue, 13 Aug 2002 16:58:10 -0700
At 3:32 PM 8/13/02, John C. Randolph wrote:
>On Tuesday, August 13, 2002, at 03:20 PM, Kevin Elliott wrote:
>
>> if(myval % 2 == 0)
>
><curmudgeon>
>
>I'd just like to point out that even though everyone else who answered
>this question did a mod and compare, the result of the modulus operator
>is an integer, which in C is a perfectly valid boolean value.
>
>"These kids today don't know the simple joy of saving four bytes of
>page-0 memory on a 6502" - unknown
>
></curmudgeon>
Yes, it's safe to omit the compare in this case, but just beware of the
cases it's not safe. Many (including Apple-supplied) headers have the
habit of defining a "Boolean" type as a small integer value such as an
unsigned short or unsigned char.
If you have code like the following,
Boolean result = flags & mask; /* instead of (flags & mask) == 0 */
if (result)
{
}
the problem is that (flags & mask) might result in an unsigned long
which then gets converted to the shorter Boolean form, thereby throwing
away the high bits and not producing the expected results.
The moral to the story: beware of any type named 'Boolean'.
HTH,
Andrew.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.