Sometimes, you feel it necessary that there should be a function so as to get all types of input. It should also be able to go back. You can make a function which will be able enough to admit a pointer; it can also get different kinds of argument. Even you can make a function that are able to carry on the avg(2, 4, 34.4, 22, 54.1).
The cstdarg is a header file, which is used in a function for giving changed number of arguments. It requires four branches. The first one is va_list. It saves the record of arguments. The second is va_start. It makes the list to start. The third one is va_arg. It starts the coming argument back inside the list. For the cleaning procedure, va_end is used. When a function has undefined numbers of arguments, then at the end an ellipsis is used. It will explain the compiler that this function will have a lot of arguments.
The example of va_list is:
va_start gets 2 arguments and known as macro, one is va_list and the other is variable’s name which comes first the ellipsis (…). That’s why, a_function starts a_list with the help of va_start.
The va_arg gets a variable category and a va_list. It gives back the coming argument to the type, which is defined to it. Then it comes to the other argument.
An example is show the working of these functions.
using namespace std;
double average ( int num, ... )
va_list arguments; // A space to save the arguments
double sum = 0;
va_start ( arguments, num ); // Starting the arguments in order to save the values
// in the num
for ( int y = 0; y < num; y++ ) // Loop will run till the addition of all numbers
sum += va_arg ( arguments, double ); // Put the coming value in the argument list for
va_end ( arguments ); // clears the list
return sum / num; // Gives back a few numbers
cout<< average ( 4, 2.2, 42.3, 4.8 ) <<endl;
cout<< average ( 9 4.3, 2.2, 4.1, 2.5, 6.3 ) <<endl;
It is recommended not to use variable arguments all the time. The reason is that a value means something else and it is assumed in another type. Like a void pointer is supposed as an integer.