Extra comma in macro

Advanced options using macros in C ++

Why does the author of one of the posts in this thread use an extra comma in the macro here?

#define PRINT_STRING_MACRO_CHOOSER(...) \ GET_4TH_ARG(__VA_ARGS__, PRINT_STRING_3_ARGS, \ PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS, ) 
+4
source share
1 answer

This is done so that GET_4TH_ARG will always come with its vararg arguments (which is a language requirement).

For example, without him

PRINT_STRING_MACRO_CHOOSER("Hello, World")

will expand to

GET_4TH_ARG("Hello, World", PRINT_STRING_3_ARGS, PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS)

but not

GET_4TH_ARG("Hello, World", PRINT_STRING_3_ARGS, PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS,)

The first form does not contain vararg arguments (and therefore will not be a valid call), where the second form provides an empty vararg argument for GET_4TH_ARG .

From the C ++ standard: [cpp.replace]/4 :

If the list identifier in the macro definition does not end with an ellipsis, the number of arguments (including those arguments that do not consist of preprocessing tokens) when calling a functionally similar macro should equal the number of parameters in the macro definition. Otherwise, the call must have more arguments than the macro definition (except ...) ....

+5
source

All Articles