C Conditional Compilation

Intermediate
6 min read
Updated: Nov 2026
1 example

What Is Conditional Compilation?

Conditional compilation keeps or removes blocks of source before compilation. #ifdef / #ifndef test whether a macro exists; #if tests a constant expression and works with defined(NAME), #elif, and #else. Use it for debug code, platform differences, and feature switches.

Remember
#if defined(DEBUG) && LEVEL >= 2
    /* ... */
#elif defined(DEBUG)
    /* ... */
#else
    /* ... */
#endif

Cheat Sheet

Keep these facts handy while you work with Conditional Compilation in C.

TopicDetail
#ifdefMacro is defined
#ifConstant integer expression
defined(X)Works inside #if
Command line-DMODE=2

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Header Guards.

Example 1 — Select code by a mode macro

Change MODE and only one branch stays in the program.

C
#include <stdio.h>

#define MODE 2

int main(void) {
#if MODE == 1
    printf("mode 1: quiet\n");
#elif MODE == 2
    printf("mode 2: verbose\n");
#else
    printf("unknown mode\n");
#endif
    return 0;
}

How It Works

  1. #if MODE == 1 is false and #elif MODE == 2 is true.
  2. Only the second printf is compiled.
  3. You can override MODE with gcc -DMODE=1 if you guard the #define with #ifndef.

Edge Cases & Pitfalls

Check these before relying on Conditional Compilation in real programs.

sizeof

Using sizeof or casts in #if

The preprocessor cannot evaluate sizeof or casts; use integer constants and macros only.

nest

Unbalanced #endif

Every #if needs a matching #endif. Indent nested directives for readability.

Key Takeaways

  • Static choice: decided before compile.
  • Platform: #ifdef _WIN32.
  • Keep: do not hide too much logic in macros.

One line: Conditional compilation keeps or removes blocks of source before compilation.

Frequently Asked Questions

It builds different versions of a program from one source: debug versus release, per-platform code, and optional features.
#ifdef only checks whether a macro is defined. #if evaluates an integer expression and can combine tests with &&, ||, and defined().
Continue with "C Header Guards" next. Prevent a header from being included more than once. The C Preprocessor hub lists every topic in order.

Next: Header Guards

Prevent a header from being included more than once.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful