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.
#if defined(DEBUG) && DEBUG > 1 puts("verbose"); #endif
Try it
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.
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
#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 orenumconstants in#if: the preprocessor runs before types exist. Use<limits.h>macros orstatic_assertfor such checks. - Unknown identifiers evaluate to 0, which hides typos. Prefer
defined(X)for "is this switched on" tests, and#if Xonly for numeric values. - Arithmetic is done in
intmax_t/uintmax_t, notint, so#if -1 < 0ubehaves differently from the same expression in C code. #if 0is 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
#endifto keep long blocks readable. - Headers use
#ifndeffor include guards. - Do not use conditionals to fork whole functions' meaning when a
static inlinewrapper would do; every configuration you do not build is code that silently rots.