0
0
CHow-ToBeginner · 3 min read

How to Use #if #elif #else in C for Conditional Compilation

In C, use #if, #elif, and #else to conditionally compile code based on constant expressions. The #if checks a condition, #elif provides alternative conditions, and #else handles all other cases. These directives help include or exclude code before the program runs.
📐

Syntax

The #if directive checks if a condition is true to include code. #elif (else if) checks another condition if the first is false. #else includes code if all previous conditions are false. Always end with #endif to close the conditional.

c
#if CONDITION1
    // code if CONDITION1 is true
#elif CONDITION2
    // code if CONDITION2 is true
#else
    // code if none of the above conditions are true
#endif
💻

Example

This example shows how to use #if, #elif, and #else to print different messages depending on a defined constant.

c
#include <stdio.h>

#define VALUE 2

int main() {
#if VALUE == 1
    printf("Value is one.\n");
#elif VALUE == 2
    printf("Value is two.\n");
#else
    printf("Value is something else.\n");
#endif
    return 0;
}
Output
Value is two.
⚠️

Common Pitfalls

Common mistakes include using variables instead of constants in conditions, forgetting #endif, or mixing runtime if with preprocessor #if. The preprocessor only evaluates constant expressions before compiling.

c
#define NUMBER 5

// Wrong: using a variable in #if (not allowed)
// int x = 5;
// #if x == 5
//     // error
// #endif

// Right: use constants or macros
#if NUMBER == 5
    // code here
#endif
📊

Quick Reference

DirectivePurpose
#ifStarts a conditional block, includes code if condition is true
#elifChecks another condition if previous #if or #elif was false
#elseIncludes code if all previous conditions are false
#endifEnds the conditional block

Key Takeaways

Use #if, #elif, and #else to conditionally compile code based on constant expressions.
Always close conditional directives with #endif to avoid compilation errors.
Preprocessor conditions must use constants or macros, not variables.
These directives control what code the compiler sees before compiling.
Mixing runtime if and preprocessor #if can cause confusion; they work differently.