...

/

Variable Number of Arguments

Variable Number of Arguments

Learn to find the maximum in a function that receives a variable number of arguments.

We'll cover the following...

Problem

Write a program that has a function findmax( ) that receives a variable number of arguments and finds and returns the maximum out of them.

Coding solution

Here is a solution to the above problem.

Press + to interact
#include <iostream>
#include <cstdarg>
int findmax ( int, ...) ;
int main( )
{
int max ;
max = findmax ( 5, 23, 15, 1, 92, 50 ) ;
std :: cout << "maximum = " << max << std :: endl ;
max = findmax ( 3, 100, 300, 29 ) ;
std :: cout << "maximum = " << max << std :: endl ;
return 0 ;
}
int findmax ( int count, ... )
{
int max, i, num ;
va_list ptr ;
va_start ( ptr, count ) ;
max = va_arg ( ptr, int ) ;
for ( i = 1 ; i < count ; i++ )
{
num = va_arg ( ptr, int ) ;
if ( num > max )
max = num ;
}
return ( max ) ;
}

Explanation

Look at the prototype of findmax( ). The ellipses ( … ) indicate that the number of arguments after the first argument would be variable.

Observe the two calls to findmax( ). In the first call, we passed 6 arguments. In the second, we ...