Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic macro expansion's going wrong

Consider the following code

#define COMB(F, ...) F(__VA_ARGS__)


#define ADD(X, Y) (X + Y)


int foo() {
    return COMB(ADD, 1, 2);
}

I have done some experiments on Godbolt. Microsoft VS v19.22 (with /E flag) fails at preprocessing the macro's. It gives the following error

int foo() {

    return (1, 2 + );

}

example.cpp

<source>(8): warning C4003: not enough arguments for function-like macro invocation 'ADD'

GCC (with -E flag) simply outputs as expected

int foo() {
    return (1 + 2);
}

I took a look at the C99 standard. But I am still not sure which compiler is doing it right?

I hope somebody can help me with clarifying this.

like image 473
Aris Koning Avatar asked Jul 12 '26 02:07

Aris Koning


2 Answers

I think gcc is correct. Although C11 6.10.3/12 describes the invocation of COMB as having two arguments (ADD and 1,2), once COMB has been expanded the resulting token sequence is ADD ( 1 , 2 ), and 6.10.3.4/1 is clear that the result of the first replacement is rescanned as a preprocessing token sequence. An argument from a previous step that consisted of multiple tokens is not somehow glued into a single token for rescanning.

6.10.3.4/1:

After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing token sequence is then rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace

like image 188
M.M Avatar answered Jul 14 '26 18:07

M.M


MSVC expands __VA_ARGS__ after passing it into the macro. You'll have to manually expand the macro like this:

#define EXPAND(x) x
#define COMB(F, ...) EXPAND(F(__VA_ARGS__))

#define ADD(X, Y) (X + Y)

GCC is the correct compiler in this case.

like image 45
S.S. Anne Avatar answered Jul 14 '26 18:07

S.S. Anne