When you do the comparison d <= (TOTAL_ELEMENTS-2)
, a type conversion is performed. d
is of type signed int
while (TOTAL_ELEMENTS-2)
is of type size_t
, which is an unsigned type. The rules of C say that when an operator has a signed and an unsigned argument, and the unsigned argument is of greater or equal size to the signed argument, then the signed argument is converted to unsigned.
That is, the comparison ends up as:
(size_t) d <= (TOTAL_ELEMENTS-2)
And because size_t
is unsigned, (size_t) -1
is a really, really large number, not -1 any more. For a 32-bit size_t
it would be 232 - 1 = 4,294,967,295.
To fix this, you can explicitly cast the right-hand side to signed int:
d <= (int) (TOTAL_ELEMENTS-2)
Or, better, just get rid of the weird negative indexing and such.
For future reference, turn on all the compiler warnings you can. gcc, for instance, will print a warning if you turn on -Wall -Wextra
:
$ gcc -o arrayprint -Wall -Wextra -ansi arrayprint.c
arrayprint.c: In function ‘main’:
arrayprint.c:11: warning: comparison between signed and unsigned