Re: Preprocessor possibilities



Christopher Benson-Manica a écrit :
Is it possible to write a macro (in unextended C89) such that

TEST( int, (1,2,3) );

expands to

int array[]={ 1,2,3 };

?  I strongly suspect that it is not, but I don't wish to overlook a
solution if one exists.

The obvious way :

#define TEST(T, a, b, c)\
   T array[] = {a, b, c}

int main(void)
{

   TEST (int, 1, 2, 3);

   return 0;
}

But I guess you want a variable list. Il suggest this :

#include <stdio.h>

int main(void)
{

   int array[] =
      {
#define ITEM(value)\
      value,
#include "test.itm"
#undef ITEM
      };

   size_t i;

   for (i = 0; i < sizeof array / sizeof *array; i++)
   {
      printf ("array[%u] = %d\n", (unsigned) i, array[i]);
   }

   return 0;
}

with:

/* test.itm */

ITEM (12)
ITEM (34)
ITEM (56)

which is a trick I got here on c.l.c a few years ago. I'm using it day
and night to automate code generation ! Very powerful ! (Perfect to give
a string to an enum, for example...)

--
A+

Emmanuel Delahaye
.



Relevant Pages