Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ macro with variable number of arguments [duplicate]

Tags:

c++

macros

Possible Duplicate:
C/C++: How to make a variadic macro (variable number of arguments)

I need macro that will expand in a array that contains it's arguments. For example:

#define foo(X0) char* array[1] = {X0}
#define foo(X0, X1) char* array[2] = {X0, X1}

and so on. My problem is that I need to use foo with variable number of arguments, so I want to be able to use foo("foo0") but also to use foo("foo0", "foo1", "foo2"..."fooN"). I know it's possible to have:

#define foo(...)
#define foo_1(X0) ..
#define foo_2(X0, X1) ..
#define foo_3(X0, X1, X2) ..
#define foo_N(X0, X1, ... XN) ..

And use ____VA_ARGS____, but I don't know how may I expand foo in foo_k macro depending on it's parameter count? Is this possible?

like image 618
Mircea Ispas Avatar asked Mar 12 '11 14:03

Mircea Ispas


People also ask

What is __ Va_args __ in C++?

To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.

How do you define variadic arguments?

Here is an example: #define eprintf(...) fprintf (stderr, __VA_ARGS__) This kind of macro is called variadic. When the macro is invoked, all the tokens in its argument list after the last named argument (this macro has none), including any commas, become the variable argument.

How many arguments macro can have in C?

For portability, you should not have more than 31 parameters for a macro. The parameter list may end with an ellipsis (...).

What is the correct format for naming a macro with multiple arguments?

Macros with arguments To create a macro with arguments, put them in parentheses separated by commas after the macro name, e.g. then BadSquare(3+4) would give 3+4*3+4, which evaluates to 19, which is probably not what we intended.


1 Answers

How about:

#define FOO( ... ) char* x[] = { __VA_ARGS__ };
like image 64
JoeSlav Avatar answered Oct 16 '22 06:10

JoeSlav