Possible Duplicate:
A riddle (in C)
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
Problem is, the
TOTAL_ELEMENTSis an unsigned value and on the implementation you’re trying this on, it’s probablyunsigned long int. The comparison will try to promote the integer value ofd,-1, to anunsigned long, which will result in something like 0xFFFFFFFFFFFFFFFF and that’s greater than 7-2=5 (the result ofTOTAL_ELEMENTS-2); therefore, the loop condition is evaluated to false and the body is never executed. If you explicitly cast awayunsignedfrom the right hand side of the comparison operator, it should work just fine:(By the way, the
COUNTOFmacro is generally defined as:and is used like
COUNTOF(array), rather than defining a macro for each array. This is not the reason you’re seeing the problem, however; your macro is being used correctly here. This is completely orthogonal to the issue, and it’s just a coding style advice.)