Reputation: 49329
I am trying to come up with a macro to do something like the following,
MY_MACRO(type,name,args...)
MY_MACRO(int,_array,1,2,3)
and expand to,
int _array[] = {1,2,3};
coll* __array = my_call(&array[0],&array[1],&array[2]);
is this possible with/without compiler specific magic?
my_call expects variable number of arguments and I do not want to pass the array directly.
EDIT: I am already using the accepted answer from the following SO question for var args,
Macro returning the number of arguments it is given in C?
So I can find how many elements are in the array.
Upvotes: 3
Views: 5472
Reputation: 30969
You can start with (C99, not GCC-specific):
#define MY_MACRO(type, name, ...) \
type name[] = {__VA_ARGS__};
The my_call
part will be more difficult; there are macros online that can count the number of arguments, but you will need something like Boost.Preprocessor (which should work in C) to apply my_call
to the consecutive elements of the array. How many elements do you have as a maximum? You might want something like:
#define COUNT(...) COUNT2(__VA_ARGS__, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define COUNT2(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, count, ...) count
#define PP_CAT(a, b) PP_CAT2(a, b)
#define PP_CAT2(a, b) a ## b
#define CALL_MY_FUNC(arr, ...) my_call(PP_CAT(ITER_, COUNT(__VA_ARGS__))(arr));
#define ITER_0(arr) /**/
#define ITER_1(arr) (arr)
#define ITER_2(arr) (arr), ITER_1((arr) + 1)
#define ITER_3(arr) (arr), ITER_2((arr) + 1)
#define ITER_4(arr) (arr), ITER_3((arr) + 1)
and so on.
Upvotes: 4