liveBook · Manning

Va_list

As explained in Modern C, Third Edition

va_list is the C library type used to represent the state of traversal through a variable argument list.

va_list is the C library type that represents traversal state for a variable argument list. Defined by <stdarg.h>, it is created with va_start, consumed with va_arg, and released with va_end. va_copy duplicates traversal state when an independent pass is needed. section 17.4.2

Forwarding arguments to formatted output

A wrapper can initialize a va_list, pass it unchanged to vfprintf, and then finish it: `va_list ap; va_start(ap, format); vfprintf(iodebug, format, ap); va_end(ap);`. This avoids manually retrieving and type-checking every argument. Before C23, va_start conventionally received the last named parameter; C23 permits omitting that second argument. section 17.4.2

The va_list interface supplies four operations:

  • va_start initializes traversal state for the variable parameters. section 17.4.2
  • va_arg retrieves the next argument using a requested type; the caller must know the argument types. section 17.4.2
  • va_copy creates a separate traversal state, while va_end terminates an initialized list. section 17.4.2

Variadic functions are not type-safe by themselves: each supplied argument must match the type expected by the consumer. This is why forwarding to a v-prefixed library function is preferable to repeating argument analysis, and why new interfaces should generally avoid variadic functions. section 17.4.2 section 17.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);

Use the compact interface listing to compare va_start, va_arg, va_copy, and va_end. section 17.4.2

How Modern C, Third Edition covers it

How deep it goes
Defines the lifecycle and four operations but stops short of specifying va_list's representation or ABI details.
Examples
Demonstrates forwarding a va_list to vfprintf and summing a sequence of double values.
What it assumes
Assumes familiarity with C function parameters and variadic functions while introducing the va_list traversal interface.
What you can do after
Apply it via <stdarg.h> to traverse variable arguments or forward them to a v-prefixed library function.
How it connects
Connects variadic functions with <stdarg.h>, va_start, va_arg, va_copy, va_end, vfprintf, and vsnprintf.

Also explained in

Compare how 2 books explain va_list →

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.