Using variable-length argument lists : Optional Arguments « Function « C++






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;
}
  
    
  








Related examples in the same category

1.optional arguments: unlimited number of parametersoptional arguments: unlimited number of parameters