0
0
CHow-ToBeginner · 3 min read

How to Use #ifdef and #ifndef in C for Conditional Compilation

In C, #ifdef checks if a macro is defined and includes the following code only if it is, while #ifndef includes the code only if the macro is not defined. These directives help control conditional compilation to include or exclude code blocks based on macro definitions.
📐

Syntax

#ifdef MACRO_NAME includes the code block if MACRO_NAME is defined.
#ifndef MACRO_NAME includes the code block if MACRO_NAME is not defined.
Both must be closed with #endif to mark the end of the conditional block.

c
#ifdef MACRO_NAME
// code included if MACRO_NAME is defined
#endif

#ifndef MACRO_NAME
// code included if MACRO_NAME is NOT defined
#endif
💻

Example

This example shows how #ifdef and #ifndef control which code runs based on whether DEBUG is defined.

c
#include <stdio.h>

#define DEBUG

int main() {
#ifdef DEBUG
    printf("Debug mode is ON\n");
#endif

#ifndef DEBUG
    printf("Debug mode is OFF\n");
#endif

    return 0;
}
Output
Debug mode is ON
⚠️

Common Pitfalls

One common mistake is forgetting to #endif, which causes compilation errors. Another is confusing #ifdef with #ifndef, leading to unexpected code inclusion or exclusion. Also, defining macros incorrectly or not at all can cause the wrong code path to be compiled.

c
#ifdef FEATURE
// code if FEATURE is defined
// Missing #endif here causes error

#ifndef FEATURE
// code if FEATURE is NOT defined
#endif

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

Quick Reference

DirectiveMeaningWhen Code Runs
#ifdef MACROIf MACRO is definedCode runs only if MACRO is defined
#ifndef MACROIf MACRO is NOT definedCode runs only if MACRO is not defined
#endifEnds the conditional blockMarks end of #ifdef or #ifndef block

Key Takeaways

Use #ifdef to include code only when a macro is defined.
Use #ifndef to include code only when a macro is not defined.
Always close conditional blocks with #endif to avoid errors.
Macros control which parts of code compile, useful for debugging or platform-specific code.
Check macro definitions carefully to ensure correct code paths.