Home > Net >  why can't compare string in #if expression in c
why can't compare string in #if expression in c

Time:05-06

i want to write code like this but i can't:

#define COLOR "red" 
#define RED "red"
#define BLUE "blue"

int main()
{

// following code can't be compiled
#if (COLOR==RED)
    cout<<"red"<<endl;
#endif

// following code can work
if(COLOR==RED)
    cout<<"red"<<endl;
else 
    cout<<"notred"<<endl;

}

so how can i realize string compare in #if expression? or may be this is not possible?

BTW i know i can realize in other ways like following:

#define COLOR 1
#define RED 1
#define BLUE 2

// can be compiled and word correctly
#if(COLOR==RED)
    cout<<"red"<<endl;
#endif

CodePudding user response:

Because #if only works with integers

expression is a C expression of integer type, subject to stringent restrictions. It may contain...

see https://gcc.gnu.org/onlinedocs/gcc-3.0.1/cpp_4.html#SEC38

CodePudding user response:

#include <iostream>

// internal functions, can be put into included header
#define TRUE 1
#define XEQUAL(a, b) a##_##b
#define EQUAL(a, b) XEQUAL(a, b)
#define XCUSTOMSTR(a) color_##a
#define CUSTOMSTR(a) XCUSTOMSTR(a)
#define XSTR(a) #a
#define STR(a) XSTR(a)

// define available colors
#define red_red TRUE
#define blue_blue TRUE
#define green_green TRUE

// optional custom names
#define color_green "grün"

#define COLOR red
#define COLOR2 green

int main() {

#if EQUAL(COLOR, red)
    std::cout << "my_"STR(COLOR)"_file.txt";
#endif

#if EQUAL(COLOR, COLOR2)
    char filename[] = "my_"STR(COLOR2)"_file.txt";
    std::cout << filename;
#endif

    std::cout << CUSTOMSTR(green);

    return 0;
}

The trick is to compare before making a string out of it.

The preprocessor can not process strings (except generate them), but it can process textual tokens!

CodePudding user response:

compiler directives are designed to disable some parts of code (not to be compiled even if they have syntax errors) the program will compile.

They are not designed to evaluate any kind of code even simple string comparison.

  •  Tags:  
  • c
  • Related