c++if-statementc-preprocessorpreprocessor-directive

Why use preprocessor #if statements instead of if() else?


I see this being done all the time for example in the Linux kernel. What is the purpose of using the preprocessor commands vs. just normal C++ if else block? Is there a speed advantage or something?


Solution

  • A preprocessor changes the C/C++ code before it gets compiled (hence pre processor).

    Preprocessor ifs are evaluated at compile-time.

    C/C++ ifs are evaluated at run-time.


    You can do things that can't be done at run-time.

    Adjust code for different platforms or different compilers:

    #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
    #include <unistd.h>
    #elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */
    #include <windows.h>
    #endif
    

    Ensure header file definitions are included only once (equivalent of #pragma once, but more portable):

    #ifndef EXAMPLE_H
    #define EXAMPLE_H
    
    class Example { ... };
    
    #endif
    

    You can make things faster than at run-time.

    void some_debug_function() {
    #ifdef DEBUG
        printf("Debug!\n");
    #endif
    }
    

    Now, when compiling with DEBUG not defined (likely a command line parameter to your compiler), any calls to some_debug_function can be optimized away by the compiler.