selfjungle Just another WordPress weblog

19Mar/110

Stringizing Operator, Token concatenation

After many years, even C shows new stuff:

Stringizing Operator

#define QUOTEME(x) #x

According to wiki:

Although macro expansion does not occur within a quoted string, the text of the macro arguments can be quoted and treated as a string literal by using the "#" directive (also known as the "Stringizing Operator").

the code

printf("%s\n", QUOTEME(1+2));

will expand to

printf("%s\n", "1+2");

Token concatenation

Token concatenation, also called token pasting, is one of the most subtle — and easy to abuse — features of the C macro preprocessor. Two arguments can be 'glued' together using ## preprocessor operator; this allows two tokens to be concatenated in the preprocessed code. This can be used to construct elaborate macros which act like a crude version of C++ templates.

For instance:

#define MYCASE(item,id) \
case id: \
  item##_##id = id;\
break

the code

MYCASE(widget,23);

will expand to

widget_23 = 23;
Tagged as: Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

 

No trackbacks yet.