STDARG - writing functions with variable argument lists.

Usage:

#include <stdarg.h>
TYPE func(TYPE arg1,TYPE arg2, ...)
{
    va_list ap;
    TYPE x;
    va_start(ap,arg2);
    x = va_arg(ap,TYPE);
       /* and so on */
    va_end(ap);
}

Description:

The #include file <stdarg.h> lets you write functions that do not have a fixed list of arguments. The file should be included before the beginning of the function definition.

The beginning of the function definition uses the normal format to declare arguments that are always present. In addition, it uses an ellipsis (...) to stand for the variable part of the argument list.

In its local declarations, the function should declare a variable of the type "va_list". This type is defined with a typedef statement in <stdarg.h>.

To begin processing the variable part of the argument list, you must issue the macro call

va_start(ap,lastparm);

where "ap" is the variable of type "va_list" and "lastparm" is the last named parameter (i.e. the one that immediately precedes the ellipsis).

To obtain an argument value from the variable part of the argument list, you use the macro call

va_arg(ap,TYPE)

where TYPE is the type of value that you want to obtain from the variable part of the argument list. The result of "va_arg" is an expression whose value is the next value from the argument list. For example,

i = va_arg(ap,int);

obtains an integer from the variable part of the argument list and assigns it to "i".

To finish processing the variable part of the argument list, you must issue the macro call

va_end(ap);

You can issue "va_end", even if you have not read every argument from the variable part of the list. After issuing "va_end", you can issue "va_start" again to go back to the beginning of the list and start over.

Argument values passed in the variable part of an argument list are converted according to the following rules:

For this reason, calls like

c = va_arg(ap,char);

will give undefined results (since "char" values are never found in the variable list -- they are all converted to "int").

See Also:

expl c lib vprintf

expl c lib vfprintf

expl c lib vsprintf

Copyright © 1996, Thinkage Ltd.