size_t size = sizeof(int);
printf("%d\n", size);
int i;
for (i = 0; i < size; i++) {
printf("%d ", i);
}
The above code (using gcc) outptus
4
0 1 2 3
size_t size = sizeof(int);
printf("%d\n", size);
int i;
for (i = -1; i < size; i++) {
printf("%d ", i);
}
This code (i is initialized to -1) outputs only 4 and nothing in the loop.
size_t size = sizeof(int);
printf("%d\n", size);
int i;
for (i = -1; i < (int) size; i++) {
printf("%d ", i);
}
Adding a cast makes the code run fine again. The output is
4
-1 0 1 2 3
What’s going wrong in the second code? Why doesn’t printf go wrong anywhere?
When
iis signed andsizeis unsigned, theniis converted to unsigned before the comparison is performed. This is part of what are called the usual arithmetic conversions.When
-1is converted to an unsigned type, the result is the largest possible value representable by the unsigned type, thusi < sizeis false wheniis-1for any value ofsize.When you use
i < (int)sizeinstead, both operands of<are of typeint, so no conversions need to be performed and since both operands are signed, you get the expected result.