C preprocessor: How to create a character literal?

前端 未结 2 1688
盖世英雄少女心
盖世英雄少女心 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:46

    While I couldn't get user4098326's answer to compile, I did get the solution below to compile and work as expected (in Code Composer Studio). The key was to use the symbol concatenation operator. Note however, that according to the standard, this should not work. A single quote (') is not a valid token nor is a single quote followed by a single character ('a). Thus those should not be able to be the input nor output of the concatenation operator. Thus, I would not recommend actually using this solution.

    #define CONCAT_H(x,y,z) x##y##z
    #define SINGLEQUOTE '
    #define CONCAT(x,y,z) CONCAT_H(x,y,z)
    #define CHARIFY(x) CONCAT(SINGLEQUOTE , x , SINGLEQUOTE )
    
    #define DO_CASE(...) case CHARIFY(__VA_ARGS__): printf("Got a " #__VA_ARGS__ "\n"); break
    

    Then:

    switch(getchar()) {
       DO_CASE(A);
       DO_CASE(a);
       DO_CASE(!);
       default: printf("Neither a nor A nor !\n"); break;
     }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题