vim wrote On 05/15/06 11:20,:
> 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;
> }
TOTAL_ELEMENTS is of type size_t, which is an unsigned
integer type, hence not the same type as the signed int d.
When the comparison operator <= has operands of different
types, it promotes one (or both) of them to a single common
type, then compares the promoted values. In your case, the
signed int d is being promoted to an unsigned type to match
the size_t, and by the rules of unsigned arithmetic the
promotion produces a very large number. The loop test fails
on the very first attempt, and the loop never executes.
Some compilers will warn about this sort of thing; read
your compiler's documentation to learn how to crank up the
warning levels. For gcc, I suggest "-W -Wall -ansi -pedantic",
possibly replacing "-ansi" with a different Standard version.
--