Loading, please wait...

Variable Argument

It’s possible to create functions that receive an unspecified number of arguments. Most programs in the text have used the standard library function printf which, as you know, takes a variable number of arguments. As a minimum, printf must receive a string as its first argument, but printf can receive any number of additional arguments.

 

The function prototype for printf is

int printf( const char *format, ... );

 

The ellipsis (…) in the function prototype indicates that the function receives a variable number of arguments of any type. The ellipsis must always be placed at the end of the parameter list. The macros and definitions of the variable arguments headers <stdarg.h> provide the capabilities necessary to build functions with variable-length argument lists. Here, demonstrates function average that receives a variable number of arguments. The first argument of average is always the number of values to be averaged.

 

Identifier

Explanation

va_list

A type suitable for holding information needed by macros va_start, va_arg, and va_end. To access the arguments in a variable-length argument list, an object of type va_list must be defined.

va_start

A macro that is invoked before the arguments of a variable-length argument list can be accessed. The macro initializes the object declared with va_list for use by the va_arg and va_end macros.

va_arg

A macro that expands to an expression of the value and type of the next argument in the variable-length argument list. Each invocation of va_arg modifies the object declared with va_list so that the object points to the next argument in the list.

va_end

A macro that facilitates a normal return from a function whose variable-length argument list was referred to by the va_start macro.