How is macro replacement performed in complex situations?
Consider the following sample code.
#define T(q) L##q
#define A(p) T("x" T(#p))
wchar_t w[] = A(a);
Is this code well-formed? What is the value of w
? Is the behavior different in C and C++? Is it different in C++0x?
I've browsed through the C++03 standard and it seems to me, that the code should be valid with w
having the value L"xa"
.
- Invocation of
A
is found, processing thereof yields the pp sequence 开发者_运维问答T ( "x" T ( "a" ) )
. - Invocation of
T
is found, yieldingL ## "x" T ( "a" )
, which in turn yieldsL"x" T ( "a" )
. - Invocation of
T
is found, yieldingL"x" L"a"
.
Is that correct? Neither EDG nor Clang accept the snippet, MSVC 9 compiles it just fine.
g++ expands to
L"x" T("a")
Macro cannot be recursive and they are pre-processed only in one shot, so T(#p)
would not be expanded again. If you wanted L"xa"
then following can be done:
#define A(p) T("x")#p
#define T(q) L##q
(It's actually L"x""a"
.)
精彩评论