Memo‎ > ‎

The ## Operator in C/C++ Macros

posted Dec 27, 2011, 10:40 AM by Teng-Yok Lee   [ updated Dec 27, 2011, 10:40 AM ]
A short example to use the ## operator for token concatenation (From GCC online documentation):

In http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html#Concatenation:

Consider a C program that interprets named commands. There probably needs to be a table of commands, perhaps an array of structures declared as follows:

     struct command
     {
       char *name;
       void (*function) (void);
     };
     
     struct command commands[] =
     {
       { "quit", quit_command },
       { "help", help_command },
       ...
     };
 

It would be cleaner not to have to give each command name twice, once in the string constant and once in the function name. A macro which takes the name of a command as an argument can make this unnecessary. The string constant can be created with stringification, and the function name by concatenating the argument with `_command'. Here is how it is done:

#define COMMAND(NAME) { #NAME, NAME ## _command } struct command commands[] = { COMMAND (quit), COMMAND (help), ... };

Comments