C preprocessor: How to create a character literal?

前端 未结 2 1701
盖世英雄少女心
盖世英雄少女心 2020-12-18 23:25

Just out of curiosity, I\'d like to know if it is possible to define a macro which can turn its argument into a character literal:

 switch(getchar()) {
   ca         


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-18 23:51

    Here's my possible solution:

    #define EVAL(...) __VA_ARGS__
    #define Q() '
    #define MYMACRO(...) Q()EVAL(__VA_ARGS__)Q()
    

    (Variadic macros are used to to support MYMACRO(,) because it would be parsed as two empty arguments.)

    I'm not sure if this code is standard-conformant due to the unmatched '. Still, I think this code works on most C99 compilers. However, this code does not work for the following characters:

    • ( which has to match with )
    • ) used to identify the start and end of the argument list
    • ' and " used for string literals and character constants
    • \, which needs escaping
    • Whitespace characters, because they are not tokens

    I'm fairly sure that there's no solution that work for (, ), ' or ", because if this was allowed, the compiler would have to change the way macros arguments are parsed.

提交回复
热议问题