c++cmacrodef

The differences between if else and #if #else #endif


I am confused between the if/else and #if/#else/#endif constructs.

  1. What are the differences between them?
  2. In which specific situations should I use each of them?

Solution

  • I am confused about the if/else and #if/#else/#endif. It seems that they have the same logic functionality.

    Can I ask what's the differences between them?

    #if, #else and #endif belong to preprocessing. They are not executed but are instructions for textual replacement. You can think of them as a kind of automatic "search & replace" feature you'd usually find in a text editor.

    if and else are run-time constructs. You can think of them as being executed while the program runs.

    Let's say you have this program:

    #include <iostream>
    
    #define VALUE 1
    
    int main()
    {
    #if VALUE == 1
        std::cout << "one\n";
    #else
        std::cout << "not one\n";
    #endif
    }
    

    When you tell your compiler to compile this program, the preprocessor will make a textual replacement before the "real" C++ code is actually compiled. It will be as if the program was:

    #include <iostream>
    
    int main()
    {
        std::cout << "one\n";
    }
    

    Now, technically you could use an if here:

    #include <iostream>
    
    #define VALUE 1
    
    int main()
    {
        if (VALUE == 1)
        {
            std::cout << "one\n";
        }
        else
        {
            std::cout << "not one\n";
        }
    }
    

    But in C++ you don't use #define for constants. You'd instead have something like:

    #include <iostream>
    
    int const value = 1;
    
    int main()
    {
        if (value == 1)
        {
            std::cout << "one\n";
        }
        else
        {
            std::cout << "not one\n";
        }
    }
    

    Perhaps the value is only known while the program executes, e.g. via user input. Then you obviously cannot use #if, which only works before the program runs. You must use if:

    #include <iostream>
    
    int main()
    {
        int value;
        std::cin >> value; // gross simplification here
    
        if (value == 1)
        {
            std::cout << "one\n";
        }
        else
        {
            std::cout << "not one\n";
        }
    }
    
    What kind of specific situations for me to choose each of them?
    

    A good guideline for a beginner would be: Use #if (or actually: #ifndef) only for include guards. Consider further uses of #if when you encounter problems that can only be solved by the preprocessor.