On Thu, 22 Sep 2005 17:57:14 +0000 (UTC),
(Walter Roberson) wrote:
> In article < .com>,
> ethan <> wrote:
> >I'd like ask some question about macro.
> >If I define a variable set, such as {5, 2, 10} or {1,3}.
> >#define X {5,2,10}
>
> There isn't any such thing as a "variable set" in C.
> The closest C comes to that is "initializers".
>
Or in C99 compound literals, or already in GNU C that the equivalent.
> >1) Is it possible to write a macro to get the number of items within X?
>
> Not without dropping in some executable code, such as a temporary
> assignment to a variable.
>
> (sizeof (int _list_copy[] = X) / sizeof(int))
>
That doesn't work, you can't assign an array at all, and sizeof can't
take a declaration, only an expression or typename. You can initialize
an array in a declaration, which at least for auto is executable.
You can just define a variable which you don't use, which doesn't need
to be and shouldn't be auto, and count it:
{ /* in whatever scope handy, 'global'=file if you like */
static /* probably */ int how_many [] = X;
count = sizeof how_many / sizeof (int);
/* since this evaluates at compile time, if there is no other use
of how_many a decent compiler will optimize it away */
}
In C99 you can also do a compound literal, which you similarly don't
(can't) use otherwise:
count = sizeof (int []) X /* is { list } */ / sizeof (int);
> >2) Is it possible to get the nth item within X?
> >e.g.
>
> >#define GET_N_ITEM(x, y) ....
>
> >GET_N_ITEM({3,2}, 2) is equal to 2.
>
> Not without dropping in some executable code.
>
>
> There are no list constructs that have independant existance at the
> preprocessor level. In C89 at least, you cannot even ask how many
> parameters were passed to a macro [but then, C89 doesn't allow any
> variation in the number of parameters passed.]
Even in C99 you can't _ask_, you can only (try to) take all the rest.
- David.Thompson1 at worldnet.att.net