When I try to print TOTAL_ELEMENTS - 2
like this:
printf("total %d\n", TOTAL_ELEMENTS - 2);
I got an warning (using gcc 4.8) saying:
test.c:8:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=]
printf("total %d\n", TOTAL_ELEMENTS - 2);
^
The warning means that TOTAL_ELEMENTS - 2
is long unsigned
. Now when you compare a signed int
with unsigned int
, that signed int is treated as unsigned. So in d <= (TOTAL_ELEMENTS-2)
, d
becomes a very high valued positive number (assuming 2's complement number system is used).
You can cast the result to int
to fix the issue.
d <= (int)(TOTAL_ELEMENTS-2)
Or if you are using the macro in many places then you can change that like this:
#define TOTAL_ELEMENTS (int)(sizeof(array) / sizeof(array[0]))