C++/Function/Optional Arguments

Материал из C\C++ эксперт
Перейти к: навигация, поиск

optional arguments: unlimited number of parameters

 
#include <stdarg.h>
unsigned int min( unsigned int first, ... )
{
    int minarg, arg;
    va_list argptr;  // Pointer to optional arguments
    if( first == 0)
        return 0;
    va_start( argptr, first);
    minarg = first;
    while( (arg = va_arg(argptr, unsigned int) ) != 0)
        if( arg < minarg)
            minarg = arg;
    va_end (argptr);
    return minarg;
}
#include <iostream>
using namespace std;
int main()
{
    cout << "The minimum of : 1 2 3 4 5 " << "is:" << min(1,2,3,4,5)
         << endl;
    return 0;
}


Using variable-length argument lists

  
#include <iostream>
#include <iomanip>
#include <stdarg.h>
using namespace std;
double average( int, ... );
int main()
{
   double w = 3.5, x = 2.5, y = 1.7, z = 1.2;
   cout << setiosflags( ios::fixed | ios::showpoint ) 
        << setprecision( 1 ) << "w = " << w << "\nx = " << x 
        << "\ny = " << y << "\nz = " << z << endl;
   cout << setprecision( 3 ) << "\nThe average of w and x is "
        << average( 2, w, x ) 
        << "\nThe average of w, x, and y is " 
        << average( 3, w, x, y ) 
        << "\nThe average of w, x, y, and z is " 
        << average( 4, w, x, y, z ) << endl;
   return 0;
}
double average( int i, ... )
{
   double total = 0;
   va_list ap;
   va_start( ap, i );
   for ( int j = 1; j <= i; j++ )
      total += va_arg( ap, double );
   va_end( ap );
   return total / i;
}