String concatenation using preprocessor

前端 未结 4 1824
南方客
南方客 2020-12-11 00:33

is it possible to concatenate strings during preprocessing?

I found this example

#define H \"Hello \"
#define W \"World!\"
#define HW H W

printf(HW)         


        
4条回答
  •  执笔经年
    2020-12-11 00:48

    From gcc online docs:

    The '##' preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each '##' operator are combined into a single token, which then replaces the '##' and the two original tokens in the macro expansion.

    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),
       ...
     };
    

提交回复
热议问题