Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

  1. Invocation of A is found, processing thereof yields the pp sequence T ( "x" T ( "a" ) ).
  2. Invocation of T is found, yielding L ## "x" T ( "a" ), which in turn yields L"x" T ( "a" ).
  3. Invocation of T is found, yielding L"x" L"a".

Is that correct? Neither EDG nor Clang accept the snippet, MSVC 9 compiles it just fine.

like image 549
avakar Avatar asked Oct 11 '22 13:10

avakar


1 Answers

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".)

like image 194
iammilind Avatar answered Oct 14 '22 05:10

iammilind