How to compare string when precompile

88 views Asked by At
#include <iostream>

#define MY_MACRO "hello"

int main() {
    #if MY_MACRO == "asdasd"
        std::cout << "The macro is not equal to hello" << std::endl;
    #else
        std::cout << "The macro is equal to hello" << std::endl;
    #endif
    return 0;
}

In this form it would not compile successfully.

#include <iostream>

#define MY_MACRO hello

int main() {
    #if MY_MACRO == asdasd
        std::cout << "The macro is not equal to hello" << std::endl;
    #else
        std::cout << "The macro is equal to hello" << std::endl;
    #endif
    return 0;
}

And in this form #if MY_MACRO == XXX would always judge as true.

So how to compare strings when pre-complie?

1

There are 1 answers

0
HolyBlackCat On

You have two options:

  1. Use numbers instead of strings, and give them names using macros:

    #define HELLO 1
    #define ASDASD 2
    
    #define MY_MACRO HELLO
    
    #if MY_MACRO == HELLO
    // ...
    #endif
    
  2. Don't use preprocessor, use a plain if (or if constexpr, the only difference here is that the latter forces the condition to be a compile-time constant). This means that all branches have to be valid (have to compile) regardless of which one is choosen:

    #define MY_MACRO "hello"
    
    int main()
    {
        if constexpr (MY_MACRO == std::string_view("hello"))
        {
    
        }
    }
    

    Or make MY_MACRO a global constexpr std::string_view variable if you don't need to override it with compiler flags.