Why doesn't my C program print the array values? [duplicate]
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_ELEMENTS
is an unsigned value and on the implementation you're trying this on, it's probably unsigned long int
. The comparison will try to promote the integer value of d
, -1
, to an unsigned long
, which will result in something like 0xFFFFFFFFFFFFFFFF and that's greater than 7-2=5 (the result of TOTAL_ELEMENTS-2
); therefore, the loop condition is evaluated to false and the body is never executed. If you explicitly cast away unsigned
from the right hand side of the comparison operator, it should work just fine:
for(d=-1;d <= (int)(TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
(By the way, the COUNTOF
macro is generally defined as:
#define COUNTOF(x) ((sizeof((x))/sizeof(*(x)))
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.)
精彩评论