Functions with Variable Numbers of Arguments
Functions that can be called with a
variable number of arguments always expect a fixed number of
mandatory
arguments—at least one is
required—and a variable number of
optional
arguments. A well-known example is
the function printf(): the format string argument
is mandatory, while all other arguments are optional. Internally,
printf() determines the number and type of the
other arguments from the information in the format string.
In the function declarator, optional arguments are indicated by three
dots (...). For example:
int printf( char *str, ... ); // Prototype
In the function definition, the optional arguments are accessed
through an object with the type
va_list
, which contains the argument information.
This type is defined in the header file
stdarg.h
, along with the macros
va_start
,
va_arg
, and
va_end
, which are used to manage the arguments.
In order to read the optional arguments, the function must carry out the following steps:
Declare an object of type
va_list. In the following example, this object is namedarglist.Invoke the macro
va_startto prepare thearglistobject to return the first optional argument. The parameters ofva_startare thearglistobject and the name of the last mandatory parameter.Invoke the macro
va_argwith the initializedarglistobject to obtain each of the optional arguments in sequence. The second parameter ofva_argis the type of the optional argument that is being obtained.After each invocation ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access