The <stdarg.h> Header File

ANSI routines for creating functions with variable numbers of arguments

Functions

va_arg
Returns the current argument in the list.
va_end
va_end helps the called function perform a normal return.
va_start
Initializes a pointer to a variable argument list.

Predefined Types

va_list
A void pointer which can be interpreted as an argument list.

va_arg

type va_arg (va_list &ap, type);

Returns the current argument in the list.

This function (also implemented as a macro) expands to an expression that has the same type and value as the next argument being passed (one of the variable arguments). The variable ap to va_arg should be the same ap that va_start initialized. Because of default promotions, you can't use char or unsigned char types with va_arg.

The first time va_arg is used, it returns the first argument in the list. Each successive time va_arg is used, it returns the next argument in the list. It does this by first dereferencing ap, and then incrementing ap to point to the following item.

va_arg uses the parameter type (which must be an expected type name) to both perform the dereference and to locate the following item. Each successive time va_arg is invoked, it modifies ap to point to the next argument in the list.


va_end

void va_end (va_list &ap);

va_end helps the called function perform a normal return.

va_end might modify ap in such a way that it cannot be used unless va_start is recalled. va_end should be called after va_arg has read all the arguments.

Note: va_end is introduced here only to increase compatibility with ANSI C. In this implementation, va_end in fact does nothing.


va_start

void va_start (va_list &ap, &lastfix);

Initializes a pointer to a variable argument list.

Some C functions, such as sprintf have a variable number of arguments. This function, together with va_arg and va_end, provides a portable way to access these argument lists. They are used for stepping through a list of arguments when the called function does not know the number and types of the arguments being passed. Function va_start (implemented as a macro) sets ap to point to the first of the variable arguments being passed to the function. It must be used before the first call to va_arg or va_end.

va_start takes two parameters: ap and lastfix. ap is explained above, and lastfix is the name of the last fixed parameter being passed to the called function.

Note: I used notation "&ap" in the prototype description, although passing by reference does not exist in ordinary C (only in C++). However, this macro is implemented in such a way that it simulates "passing by reference".


va_list

typedef void *va_list;

A void pointer which can be interpreted as an argument list.

va_list is the type of the void pointer passed to one of the functions that accepts a pointer to a list of arguments. This array holds information needed by va_arg and va_end.


Return to the main index