Possible Duplicate:
Confused about C macro expansion and integer arithmetic
A riddle (in C)
The expected output of the following C program is to print the elements in the array. But when actually run, it doesn’t do so.
#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;
}
Because
sizeofgives you an unsigned value, which you probably would have noticed had you turned up the warning level, such as using-Wall -Wextrawithgcc(a):If you force it to signed, it works fine:
What happens in detail can be gleaned from the ISO standard. In comparisons between different types, promotions are performed to make the types compatible. The compatible type chosen depends on several factors such as sign compatibility, precision and rank but, in this case, it was deemed that the unsigned type
size_twas the compatible type sodwas upgraded to that type.Unfortunately, casting
-1to an unsigned type (at least for two’s complement which is almost certainly what you’re using) results in a rather large positive number.One that’s certainly larger the the
5you get from(TOTAL_ELEMENTS-2). In other words, your for statement effectively becomes:(a) This requirement to use
extraremains a point of contention between thegccdevelopers and myself. They’re obviously using some new definition of the word “all” of which I was previously unaware (with apologies to Douglas Adams).