Showing posts with label Arguments. Show all posts
Showing posts with label Arguments. Show all posts

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:

Friday, 25 September 2009

Passing unnamed arguments in functions

It is possible to pass an unnamed argument in C++ function. The unnamed argument indicates that argument is unused. Typically unnamed arguments arise from the simplification of code or from planning ahead for extensions. In either case, leaving the argument in place, although unused, ensures that the callers are not affected by the change. Simple example as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of unnamed arguments
#include<iostream>

using namespace
std;

void
someFunc(int a, int)
{

cout<<"Only a is defined to "<<a<<endl;
cout<<"The second argument is dummy"<<endl;
}


int
main()
{

someFunc(15, 100); //100 is dummy

cout<<endl;
return
0;
}






The output is as follows: