简体   繁体   中英

C preprocessor init array

I'm writing a complex macro and I need to pass also array initializer. Basically I have trouble to do:

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

then I would call it

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

but preprocessors interprets any commas (also the one inside curly braces) as new macro parameter so it gives me error:

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

preprocessor does not 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 correct for C.

Is there a way how to do it?? For example remove braces from parameter?

I think I cracked 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 interpreted correctly as:

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

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

您可以使用宏的可变数量的参数 -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM