C Reference ยท Preprocessor
The #elif, #else and #endif directives
Reference for C #elif, #else, #endif, and the C23 #elifdef and #elifndef: choosing one branch from several, nesting rules and the common pitfalls.
#elif, #else and #endif continue and close a conditional block that began with #if, #ifdef or #ifndef. At most one branch of the chain is kept: the first one whose condition is true, or the #else branch if none are. #endif closes the whole block.
#elif expr means "else, if expr". C23 added #elifdef X and #elifndef X, shorthand for #elif defined(X) and #elif !defined(X).
#if LEVEL == 1 ... #elif LEVEL == 2 ... #else ... #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
#elif constant-expression #elifdef identifier /* C23 */ #elifndef identifier /* C23 */ #else #endif
| Directive | Description |
|---|---|
#elif expr |
Evaluated only if every earlier branch was false; same expression rules as #if. |
#elifdef X / #elifndef X |
C23 shorthand for #elif defined(X) / #elif !defined(X). |
#else |
Taken when no earlier branch was. Allowed once, as the last branch. |
#endif |
Ends the block. Required for every #if, #ifdef and #ifndef. |
Errors: #elif, #else or #endif without a matching opener, a second #else, an #elif after #else, or a missing #endif at the end of the file.
Usage notes
- Only the taken branch is evaluated. Once a branch is chosen, later
#elifexpressions are not even checked, though skipped groups must still be made of valid tokens. - Always add an
#elsethat fails (with#error) when exactly one option must be picked. A forgotten platform then breaks the build instead of silently compiling nothing. - Write
#endifcomments for long blocks:#endif /* OS_NAME */. Extra tokens on the directive line itself are ignored by some compilers and warned about by others. - C23
#elifdefcompatibility: older compilers in older modes may reject it. GCC 15 in C23 mode accepts it. When portability matters, write#elif defined(X). - Order matters: put the most specific test first.
defined(__linux__)before a generic POSIX check. - Compilers define different macros:
__linux__,_WIN32,__APPLE__are common but not standardized. See Predefined macros.