liveBook · Manning

Va_arg

As explained in Modern C

va_arg is a C standard library macro that retrieves the next argument from a va_list using a specified type.

Reading arguments from a variadic function

double sumIt(size_t n, ...) { double ret = 0.0; va_list va; va_start(va, n); for (size_t i = 0; i < n; ++i) ret += va_arg(va, double); va_end(va); return ret; } Each loop iteration retrieves the next variadic argument as a double. The function supplies the count separately; va_arg does not discover the list length or its end. section 16.5.2

va_arg is a function-like macro from stdarg.h. It receives a va_list and an explicit type, returns the next argument with that type, and advances the argument-list state. section 16.5.2

TAKEAWAY

  • Match the requested type to the arguments supplied by the caller; argument-type encoding and end detection remain the programmer’s responsibility. section 16.5.2
  • Initialize the va_list with va_start using the last named parameter, retrieve values with va_arg, and finish with va_end. section 16.5.2

How Modern C covers it

How deep it goes
Defines the macro and demonstrates a typed loop, but does not descend into va_list internals.
Examples
Uses sumIt to retrieve and sum n double values from a variadic argument list.
What it assumes
Assumes familiarity with C functions and parameters while introducing va_list and the stdarg.h interface.
What you can do after
Build it from scratch by iterating through a va_list with explicit retrieval types and caller-supplied length.
How it connects
Connects va_arg with va_list, va_start, va_end, va_copy, stdarg.h, and variadic functions.

Also explained in

Compare how 2 books explain va_arg →

Related concepts

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