Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A riddle (in C)

Tags:

c

A friend gave me a riddle:

#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]);
      getchar();
      return 0;
  }

The above code is supposed to print all the array elements, what is the problem in the code (the output is nothing)? I think the loop doesn't iterate even once?

I found out that the following code does work:

#include<stdio.h>



#define TOTAL_ELEMENTS ((sizeof(array) / sizeof(array[0])))
  int array[] = {23,34,12,17,204,99,16};

  int main()
  {
      int d;
      int x = (TOTAL_ELEMENTS-2);
      for(d=-1;d <= x;d++)
          printf("%d\n",array[d+1]);
      getchar();
      return 0;
  }

I have a theory that it's something to do with the macro, but I can't put my finger on the problem.

like image 788
Gilad Naaman Avatar asked Apr 10 '11 12:04

Gilad Naaman


People also ask

What is c puzzle?

In this C programming puzzle you need to merge two numbers. You cannot use any arithmetic, string or other functions. Optimum solution to this C programming puzzle is to use the Token-pasting operator define. Define a macros using this ## token-pasting operator gives you the merged value.


1 Answers

The problem is that (TOTAL_ELEMENTS-2) is an unsigned value. When you make the comparison d <= (TOTAL_ELEMENTS-2), both values are converted to unsigned values, and the result is false.

In your second example, x is signed so there is no problem.

like image 188
interjay Avatar answered Sep 19 '22 09:09

interjay