Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

the problem about different treatment to __VA_ARGS__ when using VS 2008 and GCC

I am trying to identify a problem because of an unusual usage of variadic macros. Here is the hypothetic macro:

#define va(c, d, ...) c(d, __VA_ARGS__)
#define var(a, b, ...)  va(__VA_ARGS__, a, b)

var(2, 3, printf, “%d %d %d
”, 1);

For gcc, the preprocessor will output

printf("%d %d %d
", 1, 2, 3)

but for VS 2008, the output is

printf, “%d %d %d
”, 1(2, 3);

I suspect the difference is caused by the different treatment to VA_ARGS, for gcc, it will first expand the expression to va(printf, "%d %d %d ", 1, 2, 3), and treat 1, 2, 3 as the VA_ARGS for macro va. But for VS 2008, it will first treat b as VA_ARGS for macro va, and then do the expansion.

Which one is correct interpretation for C99 variadic macro? or my usage falls into an undefined behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is an easy way to deal with this problem:

#define exp(...) __VA_ARGS__
#define va(c, d, ...) c(d, __VA_ARGS__)
#define var(a, b, ...)  exp(va(__VA_ARGS__, a, b))

var(2, 3, printf, “%d %d %d
”, 1);

This will do the trick on VS 2008 and it won't affect gcc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...