liveBook · Manning

Variadic arguments

As explained in Modern C, Third Edition

A variadic parameter is the ellipsis-based parameter portion of a C function declaration that accepts additional arguments.

A variadic function places an ellipsis (...) after its known parameters, allowing a call to provide an arbitrary number of additional arguments. The declaration of printf illustrates the pattern: int printf(char const format[static 1], ...). section 17.4 section 17.4.2

Treat the ellipsis as a flexible but weakly checked interface:

  • Apply the default argument promotions: narrow integer types such as char and short usually become int, and float becomes double. section 17.4.2 section 18.1.4
  • Provide an independent convention that tells the callee each argument's type; the ellipsis itself does not preserve that information for checking. section 17.4.2
  • Keep the call and the convention consistent, because incorrect format specifications or argument types can cause portability and safety problems. section 7.1 section 18.1.4

Format strings supply the missing type information

In printf("%hhu", zChar), zChar is promoted to int before the call, while %hhu tells printf to interpret the received value as unsigned char. A mismatched specification, such as printf("%d: %s\n", 65536, "a small number"), is not portable. section 17.4.2

void va_start(va_list ap, ...);
void va_end(va_list ap);
\textit{type} va_arg(va_list ap, \textit{type});
void va_copy(va_list dest, va_list src);

The va_list operations provide the basic interface for traversing variadic arguments: initialize with va_start, retrieve with va_arg, finish with va_end, and copy with va_copy. section 17.4.2

How Modern C, Third Edition covers it

How deep it goes
Defines ellipsis syntax, promotions, type conventions, portability hazards, and va_list operations, but does not detail their implementation.
Examples
Uses printf declarations, character promotion with %hhu, and nonportable format calls involving integer and pointer arguments.
What it assumes
Assumes familiarity with C function declarations, calls, and type conversions while explaining variadic promotions from their calling behavior.
What you can do after
Evaluate variadic interfaces by checking promotions, format conventions, portability, and the required va_list operations.
How it connects
Connects variadic arguments with printf, scanf, format strings, default argument promotions, and variadic macros.

Also explained in

Compare how 8 books explain variadic arguments →

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.