cconditional-statementsc-preprocessor

How to compare strings in C conditional preprocessor-directives


I have to do something like this in C. It works only if I use a char, but I need a string. How can I do this?

#define USER "jack" // jack or queen

#if USER == "jack"
#define USER_VS "queen"
#elif USER == "queen"
#define USER_VS "jack"
#endif

Solution

  • I don't think there is a way to do variable length string comparisons completely in preprocessor directives. You could perhaps do the following though:

    #define USER_JACK 1
    #define USER_QUEEN 2
    
    #define USER USER_JACK 
    
    #if USER == USER_JACK
    #define USER_VS USER_QUEEN
    #elif USER == USER_QUEEN
    #define USER_VS USER_JACK
    #endif
    

    Or you could refactor the code a little and use C code instead.