3

Possible Duplicate:
A riddle (in C)

 #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
bornfree
  • 2,308
  • 1
  • 23
  • 33

1 Answers1

7

Problem is, the TOTAL_ELEMENTS is an unsigned value and on the implementation you're trying this on, it's probably unsigned long int. The comparison will try to promote the integer value of d, -1, to an unsigned long, which will result in something like 0xFFFFFFFFFFFFFFFF and that's greater than 7-2=5 (the result of TOTAL_ELEMENTS-2); therefore, the loop condition is evaluated to false and the body is never executed. If you explicitly cast away unsigned from the right hand side of the comparison operator, it should work just fine:

for(d=-1;d <= (int)(TOTAL_ELEMENTS-2);d++)
     printf("%d\n",array[d+1]);

(By the way, the COUNTOF macro is generally defined as:

#define COUNTOF(x) ((sizeof((x))/sizeof(*(x)))

and is used like COUNTOF(array), rather than defining a macro for each array. This is not the reason you're seeing the problem, however; your macro is being used correctly here. This is completely orthogonal to the issue, and it's just a coding style advice.)

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • can you explain more on how comparison of signed and unsigned values is done or suggest me any link for it?i want to know what happens exaclty when we do such a comparison... – bornfree Jul 04 '11 at 03:56
  • @bornfree: Apart from your question addendum: The compiler would have given you a warning as well saying something like: Signed/unsigned mismatch. Warnings are important – Aamir Jul 04 '11 at 03:59
  • @Aamir:No,it didn't throw any warning...i am using gcc compiler by the way. – bornfree Jul 04 '11 at 04:02
  • @bornfree This post describes the conversion process in detail: http://stackoverflow.com/questions/50605/signed-to-unsigned-conversion-in-c-is-it-always-safe/50632#50632 – Mehrdad Afshari Jul 04 '11 at 04:08
  • Obviously this code is specially crafted to break due to unsigned arithmetic issues. The best fix would just be not to obfuscate the loop with an offset-by-negative-one index variable and instead use an unsigned or unsigned-friendly counter. – R.. GitHub STOP HELPING ICE Jul 04 '11 at 04:24
  • 1
    @R.. Of course. It's not a real "fix". It's a intuitive proof for signedness being the problem here. – Mehrdad Afshari Jul 04 '11 at 04:29