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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With