liveBook · Manning

Stringification operator

As explained in Modern C, Third Edition

Macro argument stringification is the C preprocessing technique of converting a macro argument's textual spelling into a string literal.

In a function-like macro, placing # before a parameter converts the argument's textual spelling into a string literal. For example, #X records the expression passed as X rather than its evaluated value. The preprocessing step is purely textual, allowing whitespace adjustments but not interpreting the expression. section 17.3

Use stringification with these rules:

  • Stringification does not expand macros in the argument. Therefore, STRINGIFY(__LINE__) produces "__LINE__" rather than the current line number. section 17.3
  • Add an extra expansion layer when the argument must expand first: STRGY(X) expands to STRINGIFY(X), so STRGY(__LINE__) can produce "25" on line 25. section 17.3
  • Stringify __VA_ARGS__ like any other macro parameter; the resulting text includes the commas separating the variadic arguments. section 17.4.1

Tracing the original expression

A trace macro can include the expression itself in diagnostic output: TRACE_PRINT5("my favorite variable: %g", sum) produces a line such as main:25:(sum): my favorite variable: 889, while TRACE_PRINT5("a good expression: %g", sum*argc) records (sum*argc).

How Modern C, Third Edition covers it

How deep it goes
Explains textual conversion, suppressed argument expansion, and the two-layer workaround, but stops short of preprocessing implementation internals.
Examples
Uses STRINGIFY, STRGY, TRACE_PRINT5, __LINE__, expressions, and variadic arguments as concrete examples.
What it assumes
Assumes familiarity with C function-like macros and macro parameters while establishing stringification and delayed expansion directly from examples.
What you can do after
Apply it via C macros to emit expression text and safely stringify values such as expanded line numbers.
How it connects
Connects stringification with function-like macros, macro expansion, variadic macros, __VA_ARGS__, and __LINE__.

Also explained in

Compare how 2 books explain stringification operator →

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.