Re: =?US-ASCII?Q?Re:_=3D=3FWINDOWS-1 252=3FQ=3FStupid=5Fnewbie=5Fque ?= stion_=97_determine_if_intege r?= is even or odd
Re: =?US-ASCII?Q?Re:_=3D=3FWINDOWS-1 252=3FQ=3FStupid=5Fnewbie=5Fque ?= stion_=97_determine_if_intege r?= is even or odd
- Subject: Re: =?US-ASCII?Q?Re:_=3D=3FWINDOWS-1 252=3FQ=3FStupid=5Fnewbie=5Fque ?= stion_=97_determine_if_intege r?= is even or odd
- From: "Timothy J. Wood" <email@hidden>
- Date: Tue, 13 Aug 2002 16:20:44 -0700
It is worth noting that the '%' operator is implementation specific
for negative numbers (at least this is what I recall having seen
mentioned on the gcc lists).
In particular, if with the Apr 2002 Dev Tools, running the following
program below with an input of '-3' says:
n = -3
-3 % 2 = -1
-3 & 1 = 1
So, you definitely shouldn't check whether the result is '== 1'. It
might be OK to check whether it is '!= 0' (or just use it as a boolean
expression).
I don't know if there are implementations that will return something
other than -1 or 0 for negative inputs. You would be guaranteed safety
by inverting the sign of the number first if the input is negative.
(I suppose it is worth mentioning that you might also be working on a
machine that doesn't use two's complement integers, so the '& 1'
approach might be busted for negative numbers too -- I don't now if
there are any machines like this still running though :)
-tim
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int argi, n;
for (argi = 1; argi < argc; argi++) {
n = atoi(argv[argi]);
printf("n = %d\n", n);
printf("%d %% 2 = %d\n", n, n % 2);
printf("%d & 1 = %d\n", n, n & 1);
}
return 0;
}
_______________________________________________
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.