1

Possible Duplicate:
A riddle (in C)

Can someone please explain what is wrong with this code?

#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;
}
Community
  • 1
  • 1
Romaan
  • 2,645
  • 5
  • 32
  • 63
  • 1
    What's wrong with it is the signed/unsigned issue. But what's _really_ wrong here is why you'd write this bizarre code in the first place. – paxdiablo Nov 05 '12 at 09:59
  • 1
    @paxdiablo, this was a puzzle in one of the papers I was looking at !!! Just trying to have perfection in understanding C – Romaan Nov 05 '12 at 10:01

2 Answers2

2
d <= (TOTAL_ELEMENTS-2)

d is signed: it is an int. But TOTAL_ELEMENTS is unsigned: sizeof yields a size_t value and size_t is an unsigned type.

In the <= expression d is converted to an unsigned number by the way of the usual arithmetic conversions and it becomes a huge number.

ouah
  • 142,963
  • 15
  • 272
  • 331
1

When d is -1 and is compared with TOTAL_ELEMENTS-2 (which is size_t type, ie an unsigned integer), d is promoted to a large number in an unsigned type. Then, d is greater than TOTAL_ELEMENTS-2, so the loop is never executed.

§ 6.5.8 Relational operators
If both of the operands have arithmetic type, the usual arithmetic conversions are performed.

§ 6.3.1.8 Usual arithmetic conversions
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

md5
  • 23,373
  • 3
  • 44
  • 93