Fundamentals 16 min read

Understanding C Macros: Definition, Types, Usage, and Advanced Techniques

This article explains C macro fundamentals, covering object-like and function-like macros, advanced techniques such as variadic macros, token pasting, and practical examples like NSLog, singleton, and weak/strong patterns in ReactiveCocoa in iOS development.

JD Retail Technology
JD Retail Technology
JD Retail Technology
Understanding C Macros: Definition, Types, Usage, and Advanced Techniques

Macros are named fragments of code that the preprocessor replaces wherever the name appears. They come in two forms: object-like macros, which resemble data objects, and function-like macros, which resemble function calls.

Object-like macros are often used for constants and simple shortcuts. They can span multiple lines using a backslash, and the preprocessor expands them recursively until no further macro names remain. For example, a macro defining SUM can be expanded step by step to compute expressions.

#define SUM(a,b) ((a)+(b))

Function-like macros accept parameters, but careless use can lead to multiple evaluation of arguments with side effects. The classic MAX macro, when called with an incrementing variable, causes the variable to be increased more than once, producing incorrect results.

#define MAX(a,b) ((a)>(b)?(a):(b))

To avoid double evaluation, advanced macros use GNU C statement expressions ({...}) and unique variable names generated with the __COUNTER__ macro. This ensures each argument is evaluated exactly once while preserving the macro’s inline convenience.

#define MAX(A,B) ({ __typeof__(A) __a = (A); __typeof__(B) __b = (B); __a > __b ? __a : __b; })

Libraries such as ReactiveCocoa build sophisticated macros like weakify and strongify using metaprogramming helpers (metamacro_foreach, metamacro_concat, etc.) to generate weak and strong references safely within autoreleasepools.

Common practical macros include a release‑safe NSLog that strips logging in optimized builds, a singleton macro that reduces boilerplate, and a class‑prefix macro that lets developers add a namespace‑like prefix to type names.

While macros eliminate repetitive code and enable powerful abstractions, they also increase source size, can hurt readability when nested deeply, and bypass type checking, which may introduce safety hazards.

ProgrammingCObjective‑CMacrosPreProcessor
JD Retail Technology
Written by

JD Retail Technology

Official platform of JD Retail Technology, delivering insightful R&D news and a deep look into the lives and work of technologists.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.