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 ifMACROis defined.#ifndef MACRO: Compiles the following code only ifMACROis 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
#endifExample
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
#ifdefchecks 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
| Directive | Purpose |
|---|---|
| #ifdef MACRO | Compile if MACRO is defined |
| #ifndef MACRO | Compile if MACRO is not defined |
| #if EXPRESSION | Compile if expression is true (non-zero) |
| #elif EXPRESSION | Else if, check another expression |
| #else | Compile if previous conditions are false |
| #endif | End 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.