liveBook · Manning

__VA_OPT__

As explained in Modern C, Third Edition

__VA_OPT__ is a C23 preprocessor feature that conditionally includes replacement tokens when a variadic macro receives one or more variable arguments.

__VA_OPT__ is a C23 preprocessor feature that emits its parenthesized replacement tokens only when a variadic macro receives nonempty variable arguments. In a trace macro, __VA_OPT__(,) conditionally supplies the comma separating the fixed format argument from __VA_ARGS__, keeping calls valid with or without additional arguments. section 17.4.1

One macro for optional trace arguments

#define TRACE_PRINT(...) \ fprintf(stderr, "trace: " __VA_ARGS__) A variadic formatting macro can use __VA_OPT__(,) between its fixed format parameter and __VA_ARGS__. A call with values expands with the comma; a call containing only the format string omits it. The same mechanism can stringify __VA_ARGS__, preserving the commas between supplied arguments. section 17.4.1

__VA_OPT__ also supports preprocessor dispatch patterns:

  • Concatenate a suffix conditionally, selecting between macros such as FPRINTF_II and FPRINTF_IIIplus. section 17.4.1
  • Append a comma only when forwarding optional arguments to functions such as strtod and strtoul. section 17.5
  • Dispatch through macro families that provide defaults, reject excessive arguments, and preserve explicitly supplied values. section 17.5

How Modern C, Third Edition covers it

How deep it goes
Explains conditional commas, stringification, token concatenation, and default-argument dispatch, stopping short of broader preprocessor internals.
Examples
Demonstrates trace printing, fprintf dispatch, stringified argument lists, and wrappers supplying defaults to string-conversion functions.
What it assumes
Assumes familiarity with function-like macros, variadic parameters, __VA_ARGS__, and macro expansion.
What you can do after
Apply it via C23 variadic macros to conditionally insert separators, forward optional arguments, and select expansion targets.
How it connects
Connects variadic macros, __VA_ARGS__, macro stringification, token concatenation, and macro dispatch.

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.