FrozenHeart
FrozenHeart

Reputation: 20746

Additional comma in the macro

Optional Parameters with C++ Macros

Why is the author of one of the messages in this thread use additional 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, )

Upvotes: 4

Views: 238

Answers (1)

Mankarse
Mankarse

Reputation: 40613

This has been done so that GET_4TH_ARG will always be supplied with its vararg arguments (which is a requirement of the language).

For example, without it,

PRINT_STRING_MACRO_CHOOSER("Hello, World")

would expand to

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

rather than

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

The first form does not provide any vararg arguments (and so would not be a valid call), where the second form does provide an empty vararg argument to GET_4TH_ARG.

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

If the identifier-list in the macro definition does not end with an ellipsis, the number of arguments (including those arguments consisting of no preprocessing tokens) in an invocation of a function-like macro shall equal the number of parameters in the macro definition. Otherwise, there shall be more arguments in the invocation than there are parameters in the macro definition (excluding the ...). ...

Upvotes: 5

Related Questions