Core Directives
The preprocessor uses a specific set of directives to manage conditional blocks. Every conditional block must be terminated with an#endif directive.
#if: Evaluates an integer constant expression. If the expression evaluates to a non-zero value (true), the subsequent code block is included.#ifdef: Checks if a specific macro identifier is currently defined.#ifndef: Checks if a specific macro identifier is currently not defined.#elif: Acts as an “else if”, evaluating a new constant expression if the preceding#ifor#elifevaluated to zero.#else: Provides a fallback block of code if all preceding conditions in the chain evaluated to zero.#endif: Terminates the conditional compilation block.
Syntax Visualization
Expression-Based Evaluation:The defined Operator
For more complex conditions, the preprocessor provides the defined unary operator. It yields 1 if the identifier is defined as a macro, and 0 otherwise. This operator allows developers to combine multiple definition checks using standard C logical operators (&&, ||, !) within a single #if or #elif directive.
#ifdef MACRO is strictly equivalent to #if defined(MACRO).
Evaluation Rules and Mechanics
When the preprocessor encounters an#if or #elif directive, it follows a strict sequence of evaluation:
- Macro Expansion: All macros within the controlling expression are expanded, except those that are operands to the
definedoperator. - Identifier Replacement: Any remaining identifiers that have not been expanded into macros (excluding keywords like
defined) are implicitly replaced with the integer constant0. - Expression Evaluation: The resulting expression is evaluated according to the rules of C integer arithmetic.
- The expression must resolve to an integer constant expression.
- Floating-point constants, string literals, and cast operators are strictly prohibited and will result in a preprocessing error.
- The preprocessor supports standard relational (
<,<=,>,>=,==,!=), logical (&&,||,!), and bitwise (&,|,^,<<,>>,~) operators. - Because the evaluation happens before compilation, the
sizeofoperator cannot be used, as the preprocessor has no knowledge of target architecture data types or memory layouts.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More





