liveBook · Manning

Macro

As explained in Modern C, Third Edition

A macro definition is a preprocessing directive that associates a macro name and optional parameters with replacement text.

A macro associates a name, and optionally parameters, with replacement text through a preprocessor #define. The preprocessor expands that text early in compilation, before ordinary compiler analysis. A definition contains #, define, an identifier, replacement text, and a terminating newline. section 5.6.3 section 17.1

Named constant

# define M_PI 3.141'592'653'589'793'238'46 Every later occurrence of M_PI is replaced by the specified double constant. Macro names conventionally appear in all capitals, making textual replacement visually distinct from ordinary identifiers. section 5.6.3

Use macros deliberately because replacement text can contain almost any C text:

  • Reserve them for initialization constants or compiler magic when a macro is appropriate. section 10.2.1
  • Keep macro control flow visible and unsurprising; hidden return statements and dangling-else interactions can mislead readers. section 10.2.1
  • For function-like macros, match arguments to identifier parameters, expand arguments recursively, and substitute them into copied replacement text. section 17.1
  • Parenthesize arguments and evaluate each argument only once when designing function-like macros. section 17.1
#define BYTECOPY(T, S) memcpy(&(T), &(S), MINSIZE(T, S))

This compact function-like macro shows parameters substituted into a memcpy-based replacement expression. section 17.1

How Modern C, Third Edition covers it

How deep it goes
Defines replacement structure and function-like expansion rules, then stops short of a complete preprocessing specification.
Examples
Uses M_PI, BYTECOPY, argument substitution, hidden return control flow, and dangling-else examples.
What you can do after
Build it from scratch by defining textual constants and function-like replacements with explicit argument and control-flow safeguards.
How it connects
Connects preprocessing with named constants, enumeration constants, compile-time constants, function-like macros, and control-flow hazards.

Also explained in

Compare how 9 books explain macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.