Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro with variable length of parameters

Tags:

c

gcc

Is there a way to #define a macro with variable length of parameters?

#define CALL(ar1, ar2, ar3)
do something
#endif

in C code

CALL(0);
CALL(0,1);
CALL(0,1,2)

all invoke the above CALL macro. If ar2, ar3 not used, preprocessor just ignore the line with ar2 or ar3.

like image 318
richard Avatar asked Feb 07 '13 19:02

richard


People also ask

What are the macros that are designed to support variable length arguments?

To support variable length arguments in macro, we must include ellipses (…) in macro definition. There is also “__VA_ARGS__” preprocessing identifier which takes care of variable length argument substitutions which are provided to macro.

What is variable length parameter?

A variable-length argument is a feature that allows a function to receive any number of arguments. There are situations where a function handles a variable number of arguments according to requirements, such as: Sum of given numbers. Minimum of given numbers and many more.

Can macros have parameters?

You can define macro values to include parameter symbols. The first parameter symbol is %1, the second is %2, and so on. You pass values for the parameters when you reference the macro symbol name for expansion.

How do I use variadic macros?

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.

What is __ Va_args __ C++?

macro expansion possible specifying __VA_ARGS__ The '...' in the parameter list represents the variadic data when the macro is invoked and the __VA_ARGS__ in the expansion represents the variadic data in the expansion of the macro. Variadic data is of the form of 1 or more preprocessor tokens separated by commas.


1 Answers

Yes, take a look at this one: http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html

Key word is __VA_ARGS__ ( Variadic Macros ):

A macro can be declared to accept a variable number of arguments much as a function can. The syntax for defining the macro is similar to that of a function. Here is an example:

 #define eprintf(...) fprintf (stderr, __VA_ARGS__)
like image 178
Leo Chapiro Avatar answered Sep 18 '22 05:09

Leo Chapiro