In the comparison index <= TOTAL_ELEMENTS-2
, the left-hand side index
has the type int
, and the right-hand side TOTAL_ELEMENTS-2
has the type size_t
¹. The two operands of the operator have different types, so they need to be converted to a common type. The common type always has the larger of the two sizes², which is size_t
(which may be the same as unsigned int
on 32-bit machines, but it usually larger on 64-bit machines). And the common type is unsigned in this case, because the right-hand side is at least as large.
The common type is always chosen so that it can represent the maximum positive value of both types. If this results in an unsigned type then it can't represent negative values.
Here the variable index
is an array index, so it should have the type size_t
. The type int
may be too small to represent all array indices.
size_t
is an unsigned type; unsigned values are easier to manipulate, and have predictable behavior on overflow, so generally speaking you should use unsigned types unless you need negative values. (Overflow is still a problem with unsigned types, but at least the behavior is well-defined so the problem is easier to debug.) Here there's no point in having a variable with negative values: use index
as the array index, instead of the array index minus one, and then it'll start at 0 instead of 1.
size_t index;
for(index = 0; index <= TOTAL_ELEMENTS-1; index++) {
printf("%d\n", array[index]);
}
¹ Or unsigned int
if size_t
is smaller than int
, e.g. if it's unsigned short
, but it would be very unusual for a C implementation to be like this.
² In technical terms, the larger of the two ranks.