1

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

Community
  • 1
  • 1
ZoomIn
  • 1,237
  • 1
  • 17
  • 35

1 Answers1

7

sizeof() is of type unsigned, wile d is signed.

you check if d is smaller then an unsigned integer. Thus, the signed d is converted to unsinged.

But the bits representaion of the signed -1 when read as unsigned is greater then 2^31, and obviously greater then TOTAL_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:

#include <stdio.h>
#include <stdlib.h>
int main() { 
   unsigned int x = 50;
   int y = -1;
   printf("x < y is actually %u < %u which yields %u\n", y,x,y < x);
   return 0;
}

The above code prints:

x < y is actually 4294967295 < 50 which yields 0

amit
  • 175,853
  • 27
  • 231
  • 333