Course contentsShow
← C
Lesson 781 of 1,21911. The Preprocessor and BuildFree lesson

Basic logic with `#if` and `#else`

Basic logic with #if and #else

What you'll learn: How to tell the compiler to ignore or include specific blocks of code based on constant conditions.

Think of the preprocessor like a bouncer at the door of a club. Before the "party" (the compilation process) even starts, the bouncer looks at a checklist. If your code doesn't meet the criteria on that list, the bouncer kicks it out. The code never even makes it inside to be turned into a program.

Decisions before compilation

Standard if statements in C happen while your program is running on a user's computer. However, preprocessor directives like #if happen earlier—on your computer while you are building the app.

If an #if condition is false, the code inside is completely discarded. It’s as if those lines were deleted from the file before the compiler ever saw them. This is incredibly useful for writing code that needs to behave differently on a Windows computer versus a Mac, or for including "debug mode" features that you don't want in the final version of your app.

Using #if, #else, and #endif

The syntax looks very similar to standard C, but every command starts with a hash symbol. Every #if block must be closed with an #endif so the preprocessor knows where the conditional section ends.

#include <stdio.h>

#define VERSION 2

int main() {
    #if VERSION >= 2
        printf("Welcome to the Pro Version!\n");
    #else
        printf("Welcome to the Free Version.\n");
    #endif

    printf("Application starting...\n");
    return 0;
}

In the example above, because VERSION is defined as 2, the preprocessor will keep the "Pro Version" line and literally erase the "Free Version" line. The final program won't even contain the text "Free Version" in its memory.

Why use this?

You might wonder: "Why not just use a regular if statement?"

  1. Efficiency: Why make the computer check a condition a thousand times while the program is running if the answer is never going to change?
  2. Size: If you have a massive chunk of code meant only for testing, using #if ensures that code isn't shipped to your customers, making your final file smaller and more secure.

Key takeaway

Conditional compilation uses #if and #else to physically include or exclude code from your program before the actual compilation begins.