Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 343
frx08 Avatar asked Feb 25 '10 16:02

frx08


People also ask

Can you compare strings in C?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

Which function is used for string comparison?

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

What is #if defined in C?

The defined( identifier ) constant expression used with the #if directive is preferred. The #ifndef directive checks for the opposite of the condition checked by #ifdef . If the identifier hasn't been defined, or if its definition has been removed with #undef , the condition is true (nonzero).

What is a string comparison?

string= compares two strings and is true if they are the same (corresponding characters are identical) but is false if they are not. The function equal calls string= if applied to two strings. The keyword arguments :start1 and :start2 are the places in the strings to start the comparison.


1 Answers

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.

like image 65
Brian R. Bondy Avatar answered Oct 10 '22 15:10

Brian R. Bondy