Re: Preprocessor possibilities
- From: Emmanuel Delahaye <emdel@xxxxxxxxxxxxxx>
- Date: Tue, 13 Dec 2005 19:41:56 +0100
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 .
- Follow-Ups:
- Re: Preprocessor possibilities
- From: Christopher Benson-Manica
- Re: Preprocessor possibilities
- References:
- Preprocessor possibilities
- From: Christopher Benson-Manica
- Preprocessor possibilities
- Prev by Date: Re: FIbonacci
- Next by Date: Re: Preprocessor possibilities
- Previous by thread: Re: Preprocessor possibilities
- Next by thread: Re: Preprocessor possibilities
- Index(es):
Relevant Pages
|