Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
kjh Avatar asked Apr 06 '14 18:04

kjh


1 Answers

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.

like image 55
Paul Draper Avatar answered Oct 11 '22 04:10

Paul Draper