#include<stdio.h>
#define N (sizeof(array) / sizeof(array[0]))
main()
{
int array[5]={1,2,3,4,5};
int d;
for(d=-1;d <= N;d++)
printf("%d\n",array[d+1]);
return 0;
}
The above code is not displaying anything? Can anybody tell me why?
First, I’ll note in passing that the code as it stands will read outside the bounds of the array, since
d+1will be6at the last iteration of the loop, while the highest valid array index is4. But this isn’t the main problem with your code; as it stands, whend = -1, the conditiond <= Nwill actually evaluate tofalse, and thus the loop terminates at once without going through any iterations. The problem is that the result of the expressionsizeof(array) / sizeof(array[0])is of typesize_t, which is an unsigned integer, whiledis anint, i.e. a signed integer. Prior to the actual comparison,dis converted to asize_t(this is called type promotion), resulting in a large positive integer, and thus the expressiond <= Nevaluates to false. See this c-faq entry for more information. To really drive the point home, you may want to try the following code, and see if it works as expected:Fixing your code is fairly simple – for example, as others have suggested, rewriting the loop as
will work.