How does ## macro operator work?

  • Thread starter John H. Krueckeberg
  • Start date
J

John H. Krueckeberg

How does the macro operator ## work?

For example, given a macro like this
#define REGISTER_CLASS(_class, _symname) _class::MetaClass
instance##_class(_symname);

What would REGISTER_CLASS(Sampleclass, "Sampleclass") expand to?
 
L

Leor Zolman

How does the macro operator ## work?

For example, given a macro like this
#define REGISTER_CLASS(_class, _symname) _class::MetaClass
instance##_class(_symname);

What would REGISTER_CLASS(Sampleclass, "Sampleclass") expand to?

If you ever want to find out what the preprocessor has done, just ask the
compiler to tell you. Every compiler I know of has a command line option to
place the results of preprocessing into a file. For example, given the
following source file:

//pp.cpp:

//For example, given a macro like this

#define REGISTER_CLASS(_class, _symname)
_class::MetaClassinstance##_class(_symname);

//What would REGISTER_CLASS(Sampleclass, "Sampleclass") expand to?

int main()
{
REGISTER_CLASS(Sampleclass, "Sampleclass");
return 0;
}




the MSVC command
cl /P pp.cpp
produces a file named pp.i, containing:



#line 1 "pp.cpp"






int main()
{
Sampleclass::MetaClassinstanceSampleclass("Sampleclass");;
return 0;
}


(which may or may not reflect what you wanted the macro to actually do.)

Anyway, the ## "token pasting" operator "glues" together the preceding and
following preprocessor tokens, creating a new preprocessor token. Here's a
simple example from MSDN:

http://msdn.microsoft.com/library/d...ng/html/_predir_token.2d.pasting_operator.asp

HTH,
-leor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top