Variable Argument Lists in C using va_list


stdarg.h is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments.
It provides facilities for stepping through a list of function arguments of unknown number and type.

Declaring variadic functions


Variadic functions are functions which may take a variable number of arguments and are declared with an ellipsis ( ... ) in place of the last parameter.
Variadic functions must have at least one named parameter,

int test(int a, ...);


Defining variadic functions


The same syntax is used in a definition:

int test(int a, ...){

}

Accessing the arguments


To access the unnamed arguments, one must declare a variable of type va_list in the variadic function.
The macro va_start is then called with two arguments:

int test ( int x, ... )
{
    va_list a_list;
    va_start( a_list, x );
}
the first is the variable declared of the type va_list, the second is the name of the last named parameter of the function.

After this, each invocation of the va_arg macro yields the next argument. va_arg takes a va_list and the type of the next variable, and returns the next argument in the list in the form of whatever variable's type it is told. Once you're done, use va_end to clean up the list:


#include 
#include 
 
/* this function will take the number of values to average
   followed by all of the numbers to average */
double average ( int num, ... )
{
    va_list arguments;                     
    double sum = 0;
 
    /* Initializing arguments to store all values after num */
    va_start ( arguments, num );           
    /* Sum all the inputs; we still rely on the function caller to tell us how
     * many there are */
    for ( int x = 0; x < num; x++ )        
    {
        sum += va_arg ( arguments, double ); 
    }
    va_end ( arguments );                  // Cleans up the list
 
    return sum / num;                      
}
 
int main()
{
    /* this computes the average of 13.2, 22.3 and 4.5 (3 indicates the number of values to average) */
    printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) );
    /* here it computes the average of the 5 values 3.3, 2.2, 1.1, 5.5 and 3.3
    printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
}

留言

熱門文章