Object-Like Macros & Constants in C
Object-like macros (#define BUFFER_SIZE 1024) are textual substitution performed before compilation — every use pastes the replacement text. They define constants usable in array sizes and case labels where const int variables cannot go (const ints aren't constant expressions in C).
Parenthesize replacements fully (#define HALF(x)... is function-like; for values, (#define MASK 0xFF) harmless) — unparenthesized macro values in expressions are the classic precedence trap. Modern C still needs macros for configuration constants shared with assembly or older standards.
Textual substitution
#define LIMIT 100 pastes 100 at every LIMIT before compiling — no type, no scope, no mercy.
Constants for sizes and cases
char buf[BUFFER_SIZE]; and case ERR_TIMEOUT: need compile-time constants — macros (or enums) qualify where const int cannot.
Parenthesize values
#define SHIFT 1 << 3 used in x * SHIFT expands wrong without parens — (#define SHIFT (1 << 3)) is always safe.
Prefer enums/consts where legal
enum { MAX = 100 }; gives scoped, debuggable constants for non-array contexts — macros only where expressions demand.
#include <stdio.h> #define BUFFER_SIZE 16#define GREETING "hi" int main(void) { char buf[BUFFER_SIZE]; snprintf(buf, sizeof buf, "%s", GREETING); printf("%s\n", buf); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.