Wednesday, 30 September 2009

Passing Variable arguments in functions

Sometimes it becomes necessary to have variable number of arguments in the function. One way is to overload the function but that may be unnecessary for simple logic. We can use access variable-argument lists macros in the functions. Here is a simple example:





//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to use variable number of arguments

#include<iostream>
#include <stdarg.h> //needed for va_ macros
using namespace std;

//List Should be terminated by -1 in our case
int Add(int a,...)
{

int
total = a;
int
l_ParamVal=0;

//Declare a va_list macro and initialize it with va_start
va_list l_Arg;
va_start(l_Arg,a);

while
((l_ParamVal = va_arg(l_Arg,int)) != -1)
{

total+= l_ParamVal;
}


va_end(l_Arg);
return
total;
}


int
main()
{

cout<<"Result of Add(2) = "<<Add(2, -1)<<endl;
cout<<"Result of Add(2, 3) = "<<Add(2, 3, -1)<<endl;
cout<<"Result of Add(2, 3, 31) = "<<Add(2, 3, 31, -1)<<endl;
cout<<"Result of Add(2, 3, 31, 77) = "<<Add(2, 3, 31, 77, -1)<<endl;

cout<<endl;
return
0;
}

These type of functions that take variable number of arguments are also referred to as 'Variadic Functions'. See more details here.

The output is as follows:

No comments:

Post a Comment