Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Preprocessor

The #if, #ifdef and #ifndef directives

Reference for C conditional compilation: #if with constant expressions, #ifdef, #ifndef, defined(), and how skipped code is handled by the compiler.

The conditional directives include or skip a block of source text depending on a condition evaluated by the preprocessor. Skipped text is removed before the compiler proper sees it, so it can even contain code that would not compile on this platform. This is how one code base supports several operating systems, optional features and debug builds.

#ifdef NAME is true when NAME is currently a macro, #ifndef NAME when it is not. #if expression evaluates an integer constant expression in which any identifier that is not a macro counts as 0. Every conditional block ends with #endif.

C
#if defined(DEBUG) && DEBUG > 1
    puts("verbose");
#endif

Try it

C Choosing code at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Skipped code is never compiled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
#if constant-expression
#ifdef identifier
#ifndef identifier
    ...
#endif
Form Description
#if expr True when expr is nonzero. Supports integer arithmetic, comparisons, &&, `
#ifdef X Same as #if defined(X).
#ifndef X Same as #if !defined(X).
defined X / defined(X) 1 if X is a macro, else 0. Usable only inside #if and #elif.
#elifdef X, #elifndef X Chained forms added in C23; see #elif, #else, #endif.

Errors: a missing #endif or an #if expression that is not a valid integer constant expression (floating point, sizeof, casts, function calls) is an error.

Usage notes

  • No sizeof, casts or enum constants in #if: the preprocessor runs before types exist. Use <limits.h> macros or static_assert for such checks.
  • Unknown identifiers evaluate to 0, which hides typos. Prefer defined(X) for "is this switched on" tests, and #if X only for numeric values.
  • Arithmetic is done in intmax_t / uintmax_t, not int, so #if -1 < 0u behaves differently from the same expression in C code.
  • #if 0 is a quick way to disable a block, and it can nest even if the block contains comments. Skipped lines must still consist of valid preprocessing tokens.
  • Nesting is allowed; indent the directives or add a comment after #endif to keep long blocks readable.
  • Headers use #ifndef for include guards.
  • Do not use conditionals to fork whole functions' meaning when a static inline wrapper would do; every configuration you do not build is code that silently rots.