0
0
CHow-ToBeginner · 3 min read

How to Use Conditional Compilation in C: Syntax and Examples

Use #if, #ifdef, #ifndef, #else, and #endif directives to include or exclude code during compilation based on conditions or defined macros. This lets you compile different code parts depending on settings or platform.
📐

Syntax

Conditional compilation in C uses preprocessor directives to control which code is compiled. Here are the main parts:

  • #ifdef MACRO: Compiles the following code only if MACRO is defined.
  • #ifndef MACRO: Compiles the following code only if MACRO is not defined.
  • #if EXPRESSION: Compiles code if the expression evaluates to true (non-zero).
  • #else: Provides alternative code if the condition is false.
  • #elif EXPRESSION: Else if, checks another expression.
  • #endif: Ends the conditional block.
c
#ifdef MACRO
    // code if MACRO is defined
#else
    // code if MACRO is not defined
#endif

#if EXPRESSION
    // code if expression is true
#endif
💻

Example

This example shows how to use #ifdef and #else to compile different messages depending on whether DEBUG is defined.

c
#include <stdio.h>

#define DEBUG

int main() {
#ifdef DEBUG
    printf("Debug mode is ON\n");
#else
    printf("Debug mode is OFF\n");
#endif
    return 0;
}
Output
Debug mode is ON
⚠️

Common Pitfalls

Common mistakes when using conditional compilation include:

  • Forgetting to close the block with #endif, causing compilation errors.
  • Using undefined macros without checking, which can lead to unexpected code being compiled.
  • Overusing nested conditionals, making code hard to read and maintain.
  • Assuming #ifdef checks for macro value instead of just existence.
c
#ifdef FEATURE
// code if FEATURE is defined
// Missing #endif here causes error

// Correct way:
#ifdef FEATURE
// code
#endif
📊

Quick Reference

DirectivePurpose
#ifdef MACROCompile if MACRO is defined
#ifndef MACROCompile if MACRO is not defined
#if EXPRESSIONCompile if expression is true (non-zero)
#elif EXPRESSIONElse if, check another expression
#elseCompile if previous conditions are false
#endifEnd conditional block

Key Takeaways

Use #ifdef, #ifndef, #if, #else, and #endif to control code compilation based on macros or conditions.
Always close conditional blocks with #endif to avoid compilation errors.
Check if macros are defined before using them to prevent unexpected code inclusion.
Keep conditional compilation simple to maintain readable and clean code.
Use conditional compilation to write flexible code for different environments or debugging.