Generally if we want to add the variable number of integers or multiply the variable number of floats/integers we need separate functions for each number of arguments. Fortunately C language provides flexibility for the programmer. It supports the variable number of arguments in the function. The function signature fallows the fallowing syntax:
Returntype functionname(int n,...)
This is eclipse notation. The three dots serve for this purpose. To use this facility we have to add the stdarg header file. We need to use va_list this points to the list of the arguments.
va_start
This must be called before using the argument from the list. The syntax of this is va_start(ap,count). First argument is the list and second argument is the number of arguments passed.
va_arg(ap,datatype):
This must be called every time to get the value of the argument in a loop. The first parameter is the list and second one is the datatype of the argument.
va_end(ap):
At the end of program we have to use this to clear the resources used by the list other wise the resources will be there until the program terminates resulting in memory leaks (eating up the RAM).
va_end(ap):
At the end of program we have to use this to clear the resources used by the list other wise the resources will be there until the program terminates resulting in memory leaks (eating up the RAM).
Consider the fallowing example
#include "stdafx.h"
#include <conio.h>
#include <stdarg.h>
#include <iostream>
using namespace std;
int add(int count,...)
{
int result=0;
va_list ap;
va_start(ap,count);
for(int i=0;i<count;i++)
{
result=result+va_arg(ap,int);
}
va_end(ap);
return result;
}
int main()
{
int r;
r=add(9,1,2,3,4,5,6,7,8,9);
cout<<"\n"<<"the result of summation is :"<<r;
r=add(3,1,2,3);
cout<<"\n"<<"the result of summation is :"<<r;
_getch();
return 0;
}
The main function calls the two times the add function with the variable number of arguments. Observe that the first parameter is the number of arguments except the first one. The first call to the function has ten arguments the first one is the number of arguments and the renaming arguments are the values to calculate the addition.
No comments:
Post a Comment