Learn C
#include "preprocessor/object_macros.h"

Object-Like Macros & Constants in C

#concept

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.

#how it works
1

Textual substitution

#define LIMIT 100 pastes 100 at every LIMIT before compiling — no type, no scope, no mercy.

2

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.

3

Parenthesize values

#define SHIFT 1 << 3 used in x * SHIFT expands wrong without parens — (#define SHIFT (1 << 3)) is always safe.

4

Prefer enums/consts where legal

enum { MAX = 100 }; gives scoped, debuggable constants for non-array contexts — macros only where expressions demand.

#example
#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;
}
Output
hi
1BUFFER_SIZE pastes 16 into the array declaration — a compile-time size from a named constant.
2GREETING pastes the literal; snprintf bounds the copy to the macro-sized buffer.
3hi prints — named constants driving both storage and content.
#use cases
Array sizes and case labels requiring true constant expressions
Project-wide tuning knobs (buffer sizes, timeouts) in one header
Parenthesized replacements immune to precedence surprises
Migrating to enums and consts everywhere the language allows

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.