Wednesday, February 2, 2011

GCC precompiler - Token concatenation ##

According to wikipedia, "##" is used to combine two macro arguments together, by GCC precompiler.
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
 
switch(x) {
    MYCASE(widget,23);
}
The line MYCASE(widget,23); gets expanded here into
case 23:
  widget_23 = 23;
break;
(The semicolon following the invocation of MYCASE becomes the semicolon that completes the break statement.)

No comments:

Post a Comment