C init preprocessor array

I am writing a complex macro and I need to pass in an array initializer as well. Basically I have problems:

#define INIT_ARR(VAR_NAME,ARR_DATA) int VAR_NAME[] = ARR_DATA

      

then I would call him

INIT_ARR(myNm,{1,2,3});

      

but the preprocessors interpret any commas (also inside inside curly braces) as a new macro parameter, so it gives me an error:

error:  #55-D: too many arguments in invocation of macro "INIT_ARR" 

      

Preprocessor

doesn't ignore (), so I can do:

#define INIT_ARR(VAR_NAME,ARR_DATA) int VAR_NAME[] = {ARR_DATA}
INIT_ARR(myNm,(1,2,3));

      

but then it is interpreted as

int myNm[] = {(1,2,3)};

      

which is not true for C.

Is there a way how to do this? For example, remove the curly braces from the parameter?

+3


source to share


2 answers


I think I hacked it:

#define myArgs(...) __VA_ARGS__
#define INIT_ARR(VAR_NAME,ARR_DATA) int VAR_NAME[] = {myArgs ARR_DATA}
INIT_ARR(myArr,(1,2,3,4));

      

will be correctly interpreted as:



int myArr[] = {1,2,3,4};

      

annoying_squid's answer helped me figure it out ...

+6


source


You can use a variable number of arguments with a macro as -



#define INIT_ARR(VAR_NAME, ...) int VAR_NAME[] = {__VA_ARGS__}

      

+6


source







All Articles