"" <> writes:
> why does printf get -1 for an unsigned integer?
>
>
> #include <stdio.h>
>
> int main(void)
> {
> unsigned int u = 0;
>
> u--;
> if (u < 0)
> printf("u < 0\n");
> else
> printf("u >= 0\n");
> printf("u: %d\n", u);
> return 0;
> }
>
> $ cc a.c
> $ ./a.out
> u >= 0
> u: -1
> $
Because you lied to it. "%d" expects an argument of type int; you
gave it an argument of type unsigned int. Try "%u".
(You're probably seeing that behavior because (unsigned int)-1, or
UINT_MAX, has the same representation as (int)-1 in 2's-complement,
but that's not guaranteed.)
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"