C / Basic: Read and Construct Programs / Lesson 7
Preprocessing and named constants
Trace C preprocessing, named constants, and macro evaluation.
On this page
Lesson goals
- Distinguish macros from typed functions.
- Recognize repeated evaluation and build branches.
- Trace preprocessing replacement separately from C expression evaluation.
- Test macro grouping, repeated evaluation, and conditional compilation safely.
Preprocessing and tokens
Before compilation, the preprocessor handles directives such as include and define. A macro replaces tokens; it is not a typed variable or a function call. A symbolic constant can make a fixed limit readable, but its scope and expansion still need review. Keep directives simple while learning, and inspect the expanded source when a substitution behaves unexpectedly.
Name fixed constants
An object-like macro names a token sequence. In this example LIMIT expands to an integer constant before the compiler checks the program. An enum constant is another named integer constant that participates in the language after preprocessing. Neither mechanism creates a mutable counter. Choose names that communicate the domain, and avoid redefining a name to different meanings across headers.
#include <stdio.h>
#define LIMIT 4
enum { EXTRA = 2 };
int main(void) {
printf("%d\n", LIMIT + EXTRA);
return 0;
}
6
The macro and enum constant provide values used in the calculation.
Evaluate arguments deliberately
A function-like macro can evaluate an argument more than once because each appearance is substituted. Parentheses around parameters and the entire replacement reduce precedence surprises, but do not prevent repeated evaluation. Prefer a real function when ordinary typed evaluation is sufficient. The example uses a function so an increment argument is evaluated once for that call; do not infer an ordering among unrelated function arguments.
#include <stdio.h>
static int twice(int value) {
return value * 2;
}
int main(void) {
int n = 3;
int result = twice(n++);
printf("%d %d\n", result, n);
return 0;
}
6 4
The function receives the old value of n; the increment updates n once.
Conditional builds
Conditional compilation selects source before normal compilation, commonly for a documented platform capability or build configuration. Each branch must still be maintained and tested on a configuration that selects it. Do not use an operating-system guess as proof that a library feature exists. Keep a small set of documented build choices and make unsupported configurations fail clearly rather than silently changing behavior.
Diagnose an expansion
When a macro-related error appears, save the full compile command and locate the first diagnostic. Check the definition visible at that point, its parentheses, and whether an argument has side effects. Compiler preprocessing output can help inspect actual replacement, though the command depends on the compiler. Test the original configuration and any supported alternate branch; a single successful build cannot validate inactive code.
Separate preprocessing from C evaluation
The preprocessor operates on preprocessing tokens before the compiler translates the resulting C program. An object-like macro replaces its name with replacement tokens; a function-like macro substitutes argument tokens into its replacement list. A macro is not a typed function call. After expansion, normal C parsing, type rules, sequencing, and evaluation apply. Inspecting preprocessed output can help explain a surprising expansion, but it is not a substitute for checking whether the resulting program is well-defined.
Use macro names and constants that make their scope and purpose clear. An enum constant or a const-qualified object may be preferable when a typed language construct expresses the requirement; they have different rules and are not interchangeable in every constant-expression context. A macro can be necessary for conditional compilation or another preprocessing feature. Choose according to the interface and portability needs rather than assuming one form is universally superior.
Parenthesize macro expressions
A function-like arithmetic macro should normally parenthesize each parameter use and the entire replacement expression. Without parameter parentheses, an argument such as 1 + 2 can combine with surrounding multiplication unexpectedly. Without outer parentheses, a surrounding operator can bind to part of the expanded expression. Trace the actual tokens after substitution before calculating a result. Parentheses fix grouping, not the number of times an argument is substituted or evaluated.
A macro that uses a parameter twice can evaluate an argument twice. Passing an expression with side effects can change behavior or even create undefined behavior when modifications are unsequenced. Avoid such calls. An ordinary function can provide single evaluation of each argument expression for the call, while the order of evaluating different arguments is not generally specified by C. A static inline function can be an alternative when its type and linkage behavior suit the design.
Control conditional compilation
#if, #ifdef, #ifndef, #else, and #endif choose which tokens are included before compilation. An undefined identifier in a preprocessing #if expression is replaced as specified by preprocessing rules, but a typo can therefore silently select the wrong branch unless warnings and tests expose it. Define build configuration in a controlled place and test each supported branch. Do not confuse a preprocessor condition with a runtime if: code excluded by preprocessing is not compiled in that translation unit.
A header guard uses a consistent unique macro name to avoid processing a header body more than once in one translation unit. It does not by itself resolve incompatible declarations or prevent multiple external definitions in different translation units. Keep declarations and definitions consistent across source files. Build flags such as GCC -D can supply a macro for a particular compilation; record the exact command and compiler when reproducing a configuration issue.
Choose constants and understand scope
An object-like #define performs token replacement and has no C type of its own. A const-qualified object has a declared type and storage/lifetime rules; const prevents modification through that object’s lvalue but does not automatically make it an integer constant expression in every context. An enum constant can represent a small integer constant appropriate to its rules. Select a construct that matches the need for compile-time selection, type checking, and visibility.
Avoid assuming that a macro has function scope: once defined, it affects subsequent preprocessing tokens until undefined or until the translation unit ends. #undef stops replacement for later tokens. Keep macro names distinctive and avoid reserved identifiers. Comments and string literals are handled as specified by translation and preprocessing rules; an ordinary macro name inside a string literal is not replaced as an identifier token.
Verify expansions and behavior safely
Test a macro with a compound expression such as 1 + 2, a surrounding operator, and a side-effect-free value used more than once. Do not run a deliberately undefined unsequenced-modification example to claim a particular result. Where repeated evaluation is the lesson, use a deliberately sequenced example or a controlled function and observe its call count. Compare a function alternative for the same input and state what it guarantees.
The complete examples below use small synthetic C17 inputs and matching formats. They were compiled and run locally with warnings enabled in an isolated temporary directory. Conditional branches are fixed by the source in these fixtures; real build configurations and header layouts need separate compilation checks. The results show specific expansions and runtime behavior, not a blanket proof that a macro is safe for arbitrary arguments.
20 worked examples
1. Expand object-like constants
Problem: Calculate the sum of two fixed object-like macro replacements.
- LIMIT expands to four and EXTRA expands to two.
- The resulting C expression adds them to produce six.
#include <stdio.h>
#define LIMIT 4
#define EXTRA 2
int main(void) {
printf("%d\n", LIMIT + EXTRA);
return 0;
}
6
Why this result follows: Object-like macros replace their names with the specified tokens before translation.
2. Use a fixed multiplier
Problem: Apply an object-like macro as a multiplier in a small expression.
- SCALE expands to the integer token three.
- The translated expression multiplies three by two.
#include <stdio.h>
#define SCALE 3
int main(void) {
printf("%d\n", SCALE * 2);
return 0;
}
6
Why this result follows: The replacement tokens participate in normal C expression evaluation.
3. Expand a two-argument macro
Problem: Add two fixed integers through a parenthesized function-like macro.
- The arguments replace a and b in the replacement list.
- The resulting expression adds two and three to give five.
#include <stdio.h>
#define ADD(a,b) ((a) + (b))
int main(void) {
printf("%d\n", ADD(2, 3));
return 0;
}
5
Why this result follows: Parentheses preserve the intended grouping for each substituted argument.
4. Protect a compound argument
Problem: Double a sum using a macro with parenthesized parameter use.
- The argument tokens 1 + 2 are enclosed by the parameter parentheses.
- The grouped sum three is multiplied by two.
#include <stdio.h>
#define DOUBLE(x) ((x) * 2)
int main(void) {
printf("%d\n", DOUBLE(1 + 2));
return 0;
}
6
Why this result follows: Parameter parentheses prevent the addition from binding incorrectly with multiplication.
5. Expose missing parameter parentheses
Problem: Trace a side-effect-free macro whose argument is an unparenthesized sum.
- Substitution produces 1 + 2 * 2.
- Multiplication occurs first, producing five rather than six.
#include <stdio.h>
#define BAD_DOUBLE(x) x * 2
int main(void) {
printf("%d\n", BAD_DOUBLE(1 + 2));
return 0;
}
5
Why this result follows: A macro substitutes tokens, so ordinary precedence applies after expansion.
6. Protect the whole replacement
Problem: Multiply a macro sum by a surrounding integer.
- The outer parentheses keep the expanded sum grouped.
- Two times the sum of one and two gives six.
#include <stdio.h>
#define SUM(a,b) ((a) + (b))
int main(void) {
printf("%d\n", 2 * SUM(1, 2));
return 0;
}
6
Why this result follows: Parenthesizing the whole replacement prevents surrounding operators from splitting it.
7. Expose missing outer parentheses
Problem: Trace a macro sum used after a surrounding multiplication.
- Expansion gives 2 * (1) + (2).
- Multiplication occurs first, so the result is four rather than six.
#include <stdio.h>
#define BAD_SUM(a,b) (a) + (b)
int main(void) {
printf("%d\n", 2 * BAD_SUM(1, 2));
return 0;
}
4
Why this result follows: Parameter parentheses alone do not group the whole replacement expression.
8. Inspect repeated substitution
Problem: Evaluate a side-effect-free argument substituted twice in a macro.
- The name n appears twice in the expanded addition.
- Each read gives three, producing six.
#include <stdio.h>
#define TWICE(x) ((x) + (x))
int main(void) {
int n = 3; printf("%d\n", TWICE(n));
return 0;
}
6
Why this result follows: Repeated substitution is harmless for this fixed side-effect-free read but is still repeated.
9. Observe sequenced repeated evaluation
Problem: Count two evaluations of a macro argument using the comma operator.
- The left comma operand increments n to one and is sequenced before the right operand.
- The right operand increments n to two and supplies the expression value.
#include <stdio.h>
#define SECOND(x) ((void)(x), (x))
int main(void) {
int n = 0; int value = SECOND(++n); printf("%d %d\n", value, n);
return 0;
}
2 2
Why this result follows: The comma operator sequences these two evaluations, avoiding an unsequenced modification.
10. Compare a function alternative
Problem: Call a typed helper with a single increment expression.
- The single argument expression increments n once to one.
- The function adds its parameter value to itself and returns two.
#include <stdio.h>
static inline int twice(int x) { return x + x; }
int main(void) {
int n = 0; int value = twice(++n); printf("%d %d\n", value, n);
return 0;
}
2 1
Why this result follows: The function call evaluates this one argument expression once for the call.
11. Select a preprocessing branch
Problem: Compile a fixed enabled configuration and display its selected label.
- ENABLED expands to one in the preprocessing condition.
- The on label is defined and later passed to puts.
#include <stdio.h>
#define ENABLED 1
#if ENABLED
#define LABEL "on"
#else
#define LABEL "off"
#endif
int main(void) {
puts(LABEL);
return 0;
}
on
Why this result follows: Conditional preprocessing selects tokens before the C compiler evaluates the program.
12. Select the alternate branch
Problem: Compile a fixed disabled configuration and display its selected label.
- ENABLED expands to zero in the preprocessing condition.
- The else branch defines the off label.
#include <stdio.h>
#define ENABLED 0
#if ENABLED
#define LABEL "on"
#else
#define LABEL "off"
#endif
int main(void) {
puts(LABEL);
return 0;
}
off
Why this result follows: The excluded branch does not contribute its definition to this translation unit.
13. Test whether a macro is defined
Problem: Use a fixed defined feature macro to choose a replacement value.
- FEATURE is defined before the ifdef directive.
- The selected branch defines VALUE as seven.
#include <stdio.h>
#define FEATURE 1
#ifdef FEATURE
#define VALUE 7
#else
#define VALUE 0
#endif
int main(void) {
printf("%d\n", VALUE);
return 0;
}
7
Why this result follows: ifdef tests definition status rather than the runtime value of a C variable.
14. Distinguish definition from value
Problem: Check ifdef behavior when a macro is defined with replacement zero.
- FEATURE is defined even though its replacement is zero.
- The ifdef branch therefore selects VALUE seven.
#include <stdio.h>
#define FEATURE 0
#ifdef FEATURE
#define VALUE 7
#else
#define VALUE 0
#endif
int main(void) {
printf("%d\n", VALUE);
return 0;
}
7
Why this result follows: ifdef checks whether the name is defined, not whether its replacement is nonzero.
15. Provide a guarded default
Problem: Define a fixed default only when a macro name is absent.
- LOCAL_FLAG is not defined before the guard.
- The guarded directive defines it as three.
#include <stdio.h>
#ifndef LOCAL_FLAG
#define LOCAL_FLAG 3
#endif
int main(void) {
printf("%d\n", LOCAL_FLAG);
return 0;
}
3
Why this result follows: ifndef can provide a preprocessing default for an otherwise undefined name.
16. Replace a definition deliberately
Problem: Undefine a synthetic macro before defining a new replacement.
- The first VALUE definition is removed by undef.
- The later definition expands to five at the print call.
#include <stdio.h>
#define VALUE 3
#undef VALUE
#define VALUE 5
int main(void) {
printf("%d\n", VALUE);
return 0;
}
5
Why this result follows: Macro replacement follows the active definition at the subsequent token location.
17. Preserve a string literal
Problem: Print a literal containing the spelling of a macro name.
- WORD inside the quoted text is part of a string literal.
- It is printed as WORD rather than replaced with nine.
#include <stdio.h>
#define WORD 9
int main(void) {
puts("WORD");
return 0;
}
WORD
Why this result follows: Macro replacement operates on identifier tokens, not text inside a string literal.
18. Use an enumeration constant
Problem: Display a fixed enum constant without an object-like macro.
- The enum declares LIMIT as an integer constant with value four.
- The matching %d conversion displays four.
#include <stdio.h>
enum { LIMIT = 4 };
int main(void) {
printf("%d\n", LIMIT);
return 0;
}
4
Why this result follows: An enumeration constant is a C language construct rather than preprocessing substitution.
19. Use a const-qualified object
Problem: Read a fixed const-qualified int object in a complete program.
- The declaration initializes the object limit to four.
- The program reads and prints that value without modifying it.
#include <stdio.h>
int main(void) {
const int limit = 4; printf("%d\n", limit);
return 0;
}
4
Why this result follows: A const-qualified object has a declared C type and object semantics.
20. Square a side-effect-free value
Problem: Expand a repeated macro parameter for a fixed integer argument.
- The argument three replaces both uses of x.
- The multiplication computes nine.
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main(void) {
printf("%d\n", SQUARE(3));
return 0;
}
9
Why this result follows: The fixed argument has no side effect despite appearing twice after substitution.
Common errors and fixes
A macro changes expression precedence
- Why it happens
- Replacement tokens lack needed parentheses.
- How to fix it
- Parenthesize parameters and replacement where appropriate.
- Prevent it next time
- Test expressions with mixed operators.
An argument is evaluated twice
- Why it happens
- The macro uses its parameter twice.
- How to fix it
- Use a function when repeated evaluation is unintended.
- Prevent it next time
- Avoid side effects in macro arguments.
An alternate build fails
- Why it happens
- An inactive conditional branch was not compiled.
- How to fix it
- Compile and repair the selected branch.
- Prevent it next time
- Test all supported configurations.
20 practice exercises
1. What is LIMIT + EXTRA in the first example?
Show hint
Substitute the two fixed values before adding.
Show worked solution
LIMIT expands to four and EXTRA is two, so the expression is six.
LIMIT expands to 4 and EXTRA is 2 in the original example. The resulting expression is 4 + 2, so its value is 6.
Check your solution
- LIMIT contributes 4
- The sum is 6
2. Why can parentheses not make a macro evaluate an argument once?
Show hint
Count parameter occurrences separately from grouping.
Show worked solution
They control grouping, but substitution still inserts the argument at each use of the parameter. A function evaluates its argument for the call.
Parentheses control how substituted tokens group, but a parameter used twice still inserts its argument twice. A suitable function evaluates its single argument expression for the call rather than duplicating its tokens.
Check your solution
- Parentheses do not remove repeated parameter uses
- A function alternative avoids textual duplication
3. Given #define WIDTH 5, calculate WIDTH + 2 after preprocessing and evaluation.
Show hint
Substitute the replacement token before arithmetic.
Show worked solution
WIDTH expands to 5, so the resulting expression is 5 + 2 and evaluates to 7. The macro supplies tokens; normal C arithmetic evaluates the expanded expression.
Check your solution
- The expansion uses 5
- The result is 7
4. For #define DOUBLE(x) ((x) * 2), calculate DOUBLE(2 + 3).
Show hint
Parameter parentheses keep the compound argument grouped.
Show worked solution
The argument becomes (2 + 3) in the expansion, so the result is 5 * 2 = 10. The outer parentheses also protect the whole replacement in surrounding expressions.
Check your solution
- The sum is grouped
- The result is 10
5. For #define BAD(x) x * 2, trace BAD(2 + 3) without side effects.
Show hint
Write the substituted tokens before evaluating them.
Show worked solution
The expansion is 2 + 3 * 2. Multiplication occurs before addition, producing 8 rather than the intended doubled sum 10. Parenthesize the parameter use and the whole expression.
Check your solution
- The expansion is 2 + 3 * 2
- The actual result is 8
6. For #define SUM(a,b) (a) + (b), calculate 3 * SUM(1, 2).
Show hint
The replacement lacks outer parentheses.
Show worked solution
The expansion is 3 * (1) + (2), which evaluates to 5. Defining SUM as ((a) + (b)) would group the sum and yield 9 for this call.
Check your solution
- The actual expansion yields 5
- The grouped alternative yields 9
7. Explain why parentheses around a macro parameter cannot guarantee single evaluation of its argument.
Show hint
Count how many times the parameter appears in the replacement.
Show worked solution
Parentheses control grouping only. If a parameter appears twice, its argument tokens are substituted twice and may be evaluated twice. Avoid side-effecting arguments or use a suitable function alternative.
Check your solution
- The parameter can still appear twice
- Grouping is separate from evaluation count
8. A macro uses x twice and the argument is the side-effect-free integer variable n = 4. What sum results from ((x) + (x))?
Show hint
Both substituted reads see the unchanged value.
Show worked solution
The expansion reads n twice; each read is 4, so the sum is 8. This fixed argument has no side effect, but a side-effecting argument would require separate sequencing analysis.
Check your solution
- Both reads are 4
- The sum is 8
9. Compare a function twice(int x) returning x + x when called with ++n from n = 0.
Show hint
There is one argument expression in the call.
Show worked solution
The argument expression increments n once to 1. The function receives 1 and returns 2. After the call n is 1; this avoids substituting the increment expression twice.
Check your solution
- The returned value is 2
- n is incremented once to 1
10. For #define FEATURE 0, explain the difference between #ifdef FEATURE and #if FEATURE.
Show hint
Definition status and replacement value are different questions.
Show worked solution
#ifdef FEATURE is true because the name is defined. #if FEATURE evaluates the replacement zero and selects its false branch. Test both configurations when the distinction matters.
Check your solution
- ifdef sees a defined name
- if sees the zero value
11. A configuration macro ENABLED is 1. Which branch of #if ENABLED / #else is included?
Show hint
The preprocessing condition is nonzero.
Show worked solution
The #if branch is included because ENABLED expands to 1. The #else branch is excluded from the resulting translation unit. This choice occurs before runtime execution.
Check your solution
- The first branch is included
- The else branch is excluded
12. Explain why code excluded by #if is different from a runtime if branch that is not taken.
Show hint
The selection occurs at different stages.
Show worked solution
Preprocessing removes the excluded tokens before compilation of the translation unit. A runtime if remains part of the compiled program even if a particular execution does not enter its branch.
Check your solution
- Excluded tokens are not compiled in that unit
- A runtime branch belongs to the compiled program
13. A header guard uses #ifndef DEMO_H followed by #define DEMO_H. What problem does it address?
Show hint
Consider repeated inclusion in one translation unit.
Show worked solution
The guard prevents the guarded body from being processed again in the same translation unit after DEMO_H is defined. It does not automatically solve incompatible declarations or multiple external definitions across units.
Check your solution
- The guarded body is included once per translation unit
- Cross-unit definition problems remain separate
14. Given #define SIZE 3, then #undef SIZE and #define SIZE 6, what does a later SIZE expand to?
Show hint
Use the definition active at the later token.
Show worked solution
The undef removes the first definition. The later definition supplies replacement 6, so a subsequent SIZE expands to 6. This avoids relying on an incompatible direct redefinition.
Check your solution
- The earlier definition is removed
- The later expansion is 6
15. Given #define NAME 9, what does puts("NAME") print and why?
Show hint
The quoted characters form a string literal.
Show worked solution
puts prints NAME followed by a newline. The characters inside the string literal are not an identifier token NAME for macro replacement, so the number 9 is not substituted there.
Check your solution
- The printed word is NAME
- The literal is not replaced by 9
16. Choose a C construct for a small integer enumeration constant and state one distinction from #define.
Show hint
An enum constant is part of the C language.
Show worked solution
An enum can declare a named integer constant, for example enum { LIMIT = 4 }. Unlike an object-like macro, this is a C language declaration rather than preprocessing token replacement.
Check your solution
- LIMIT has value 4
- The enum is a language construct
17. Explain why const int limit = 4 is not interchangeable with a macro in every constant-expression context.
Show hint
const qualification and integer constant expressions have distinct rules.
Show worked solution
A const-qualified object has a type and object semantics, but its name is not automatically an integer constant expression in every C context. Select the construct required by the particular declaration or preprocessing use.
Check your solution
- The const object has a declared type
- Constant-expression requirements are checked separately
18. A macro duplicates ++n in unsequenced operands. Why should the program not claim a particular output?
Show hint
Multiple unsequenced modifications can be undefined behavior.
Show worked solution
Duplicating a side-effecting argument can create unsequenced modifications to n, making behavior undefined. Do not run it as a deterministic example. Use separate statements or a suitable function and test defined behavior.
Check your solution
- No fixed output is claimed
- The side effect is separated or evaluated once
19. How can GCC preprocessed output help diagnose a macro grouping problem for a small source file?
Show hint
Inspect the tokens after macro expansion.
Show worked solution
Run the appropriate GCC preprocessing command, such as gcc -E on an isolated source, and inspect the expanded expression. Record the exact command and compiler version, then compare the grouping with the intended C expression.
Check your solution
- The expanded expression is inspected
- Compiler and command are recorded
20. A macro is used with a compound argument and surrounding multiplication. Choose two tests to expose grouping errors.
Show hint
Test parameter grouping and whole-replacement grouping independently.
Show worked solution
Test a call such as DOUBLE(1 + 2) to expose missing parameter parentheses, and 2 * SUM(1, 2) to expose missing outer parentheses. Compare actual expanded expressions with the intended results.
Check your solution
- Compound-argument grouping is tested
- Surrounding-operator grouping is tested
Key takeaways
- Macros substitute tokens before compilation.
- Use functions to avoid unintended repeated evaluation.
- Parentheses control grouping but do not guarantee single evaluation.
- Conditional preprocessing selects tokens before runtime.
- A macro replacement has different type and scope rules from a C object or function.