Possible Duplicate:
signed to unsigned conversions
A riddle (in C)
I am trying to understand why this program is not working
#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;
}
I came across this program when I was going through automatic type conversions in C.But I don’t understand how conversions happen between signed and unsigned data types.Please explain.
Thank you,
Harish
sizeof()is of type unsigned, wiledis signed.you check if
dis smaller then an unsigned integer. Thus, the signeddis converted to unsinged.But the bits representaion of the signed
-1when read as unsigned is greater then 2^31, and obviously greater thenTOTAL_ELEMENTS-2, thus the condition is never met and you do not enter the for loop even once.Look at this code snap, it might clear up things for you:
The above code prints: