
Unsigned Pitfalls
/*
* Unsigned types can be tricky, because negatives are silently translated to
* to trash. A slightly negative value generally becomes a very large
* positive number.
*/
#include <stdio.h>
main()
{
int i;
unsigned ui, petunia;
/* See what happens when you convert from negative. */
i = -15;
ui = i;
printf("The unsigned version of -15 is %u\n", ui);
if(ui <= 0) printf("Is it likely?\n");
putchar('\n');
/* The comparison u1 <= petunia is performed correctly, but
the subtraction ui - petunia is always forced to a non-
negative value, so ui - petunia <= 0 is true only when
the two values are equal. */
ui = 4;
petunia = 0;
for(i = 4; i--;) {
printf("ui = %u, petunia = %u\n", ui, petunia);
printf("ui <= petunia: ");
if(ui <= petunia) printf("yes.\n");
else printf("no.\n");
printf("ui - petunia <= 0: ");
if(ui - petunia <= 0) printf("yes.\n");
else printf("no.\n");
putchar('\n');
--ui;
++petunia;
}
}