MSVC doesn't expand __VA_ARGS__ correctly

uj2 picture uj2 · Feb 27, 2011 · Viewed 18.8k times · Source

Consider this code:

#define F(x, ...) X = x and VA_ARGS = __VA_ARGS__
#define G(...) F(__VA_ARGS__)
F(1, 2, 3)
G(1, 2, 3)

The expected output is X = 1 and VA_ARGS = 2, 3 for both macros, and that's what I'm getting with GCC, however, MSVC expands this as:

X = 1 and VA_ARGS = 2, 3
X = 1, 2, 3 and VA_ARGS =

That is, __VA_ARGS__ is expanded as a single argument, instead of being broken down to multiple ones.

Any way around this?

Answer

Ise Wisteria picture Ise Wisteria · Feb 27, 2011

Edit: This issue might be resolved by using /Zc:preprocessor or /experimental:preprocessor option in recent MSVC. For the details, please see here.

MSVC's preprocessor seems to behave quite differently from the standard specification.
Probably the following workaround will help:

#define EXPAND( x ) x
#define F(x, ...) X = x and VA_ARGS = __VA_ARGS__
#define G(...) EXPAND( F(__VA_ARGS__) )