How to compare strings in C conditional preprocessor-directives

frx08 picture frx08 · Feb 25, 2010 · Viewed 105.1k times · Source

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

Answer

Brian R. Bondy picture Brian R. Bondy · Feb 25, 2010

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.