The expected output of the following C program is to print the array elements. 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;
}
What is the reason ?
When you do the comparison
d <= (TOTAL_ELEMENTS-2), a type conversion is performed.dis of typesigned intwhile(TOTAL_ELEMENTS-2)is of typesize_t, which is an unsigned type. The rules of C say that when an operator has a signed and an unsigned argument, and the unsigned argument is of greater or equal size to the signed argument, then the signed argument is converted to unsigned.That is, the comparison ends up as:
And because
size_tis unsigned,(size_t) -1is a really, really large number, not -1 any more. For a 32-bitsize_tit would be 232 – 1 = 4,294,967,295.To fix this, you can explicitly cast the right-hand side to signed int:
Or, better, just get rid of the weird negative indexing and such.
For future reference, turn on all the compiler warnings you can. gcc, for instance, will print a warning if you turn on
-Wall -Wextra: