Define and macros in C: solved exercise
Define and macros in C: solved exercise
If you searched for a solved #define and macros exercise in C, here are the most common patterns: symbolic constants, function-like macros, and a safe SWAP macro using the do { } while (0) idiom.
Preprocessor macros are expanded before compilation: they generate no function call overhead and have no type, which makes them fast but also dangerous if used carelessly.
Problem statement
Implement and use the following macros:
PI: constant with the value of π.SQUARE(x): returnsxsquared.MAX(a, b): returns the greater of two values.SWAP(T, a, b): swaps two variables of typeT.
C solution
Expected output
Common mistakes
- Not wrapping macro parameters in parentheses:
SQUARE(1+2)without them expands to1+2 * 1+2 = 5instead of9. - Not using
do { } while (0)for multi-statement macros: without it, a bareifmay not execute all statements in the macro. - Passing expressions with
++or function calls as macro arguments:MAX(f(), g())evaluates each argument twice. - Confusing
#definewithconst:consthas a type and scope;#defineis raw text with neither.
Practical use
#define is used for configuration constants (buffer sizes, bit masks), debug macros (DEBUG_PRINT), and minimal abstractions that avoid function call overhead on performance-critical paths.
Recommended next exercise
- Const in C: solved exercise
- sizeof in C: solved exercise
- Bitwise operators in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why wrap macro parameters in parentheses?
Because macros are text substitution. Without parentheses, SQUARE(1+2) becomes 1+2 * 1+2 due to operator precedence, giving 5 instead of 9. With parentheses: ((1+2) * (1+2)) = 9.
What is the difference between #define PI 3.14 and const double PI = 3.14?
#define is typeless, scopeless text substitution that is invisible to the debugger. const double has a type, block scope, and shows up in the debugger. In modern C, prefer const or enum for named constants.
What is the do { } while (0) idiom for in multi-statement macros?
It lets you use the macro as a normal statement: if (cond) SWAP(int, a, b); else .... Without this wrapper, only the first statement of the macro would be under the if.