Advantages of conditional-preprocessor over conditional statements

后端 未结 5 2049
遇见更好的自我
遇见更好的自我 2021-01-12 07:30

I have never worked with #if, #ifdef, #ifndef, #else, #elif and #endif

5条回答
  •  囚心锁ツ
    2021-01-12 07:56

    Conditional preprocessor doesn't work like in your first example.

    It's working with constants, you see? At compile time, it looks at the various conditions and puts in/omits source code according to it.

    For example:

    #define HAS_COMPARISON
    
    int main() {
        #ifdef HAS_COMPARISON
            int i = 0;
            if(i == 0) std::cout << "This";
            else
        #else
            std::cout << "That";
        #endif
    }
    

    With the define set, it will set the variable i and perform the comparison...in short, it will output This. If you comment that define, the entire block will not be in your program which means that it will always output That, without ever setting the variable or doing the comparison.

    That's the most common use of preprocessor defines. You can also define values and compare those to have variable behaviour with the same define, but that's another issue.

    Once more: Conditional preprocessor is evaluated at compile time, variable conditions are evaluated at runtime.

提交回复
热议问题