Alex Rivera | Logout

How to compare strings in C conditional preprocessor-directives

Asked 2010-02-25T16:56:50.760
136

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
Edit
Report

2 Answers

10

Use numeric values instead of strings.

Finally to convert the constants JACK or QUEEN to a string, use the stringize (and/or tokenize) operators.

answered 2010-02-25T17:06:42.390
1

If your strings are compile time constants (as in your case) you can use the following trick:

#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif

The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.

EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...

answered 2013-02-10T08:47:44.843

Your Answer