integer and long max/min values
ari
edelkind-freebsd-hackers at episec.com
Fri Nov 21 11:30:52 PST 2003
'Tis a bit of a waste of cpu time there.
On a two's complement system, which is probably all you'll come by, you
can find UINT_MAX by setting an unsigned integer to -1:
unsigned int i_max = -1;
A slightly more architecturally independent way of finding UINT_MAX
would be to set an unsigned integer to the complement of its zero:
unsigned int i_max = ~(unsigned int)0;
Either way, you can find the positive signed maximum by dividing your
result by two (discarding the remainder).
Try the following:
#include <limits.h>
#include <assert.h>
...
assert ((unsigned int)-1 == UINT_MAX);
assert (~(unsigned int)0 == UINT_MAX);
assert (((unsigned int)-1)/2 == INT_MAX);
assert ((~(unsigned int)0)/2 == INT_MAX);
...
Some may argue against this method, but using an unsigned complement of
zero should hold at least the portability of assuming NULL to be false.
The *_MAX macros, of course, should still be used whenever possible.
ari
Vijay.Singh at nokia.com said this stuff:
> Write a simple C program to ++ an int or long variable and see when it overflows.
>
> > -----Original Message-----
> > From: owner-freebsd-hackers at freebsd.org
> > [mailto:owner-freebsd-hackers at freebsd.org]On Behalf Of ext
> > Tim Kientzle
> > Sent: Friday, November 21, 2003 12:24 AM
> > To: Jay Sern Liew
> > Cc: freebsd-hackers at freebsd.org
> > Subject: Re: integer and long max/min values
> >
> >
> > Jay Sern Liew wrote:
> > > how do I find out the maximum (and minimum) value a long
> > and int will hold
> > > in C? (before it overflows or underflows)
> >
> > #include <limits.h>
> >
> > INT_MAX and INT_MIN are the max/min values for an int
> > LONG_MAX and LONG_MIN are the max/min values for long.
> >
> > Also, see stdint.h, which is defined in C99.
> >
> > Also, buy a good C reference book. ;-)
> >
> > Tim Kientzle
> >
> > _______________________________________________
> > freebsd-hackers at freebsd.org mailing list
> > http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
> > To unsubscribe, send any mail to
> > "freebsd-hackers-unsubscribe at freebsd.org"
> >
> _______________________________________________
> freebsd-hackers at freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
> To unsubscribe, send any mail to "freebsd-hackers-unsubscribe at freebsd.org"
More information about the freebsd-hackers
mailing list