ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Writing Variadic functions - va_start, va_arg, va_end macros

Updated on June 14, 2016

1. Variadic Function

Variadic function means a C/C++ function which takes a variable number of arguments. Think about the printf() function, which can take one are more parameters. Can you imagine how it can be implemented? Function overloading! No. Here comes the Variable Argument list in the picture. The C printf function collects the arguments in a list and inside the function, the list will be read to get all the parameters.

In this hub, let us write an Example, which will calculate the summation of numbers passed as a variable number of argument by raising it to power x passed as a standard parameter.

2. Syntax for Variadic Function

Let us say, you want to get minimum from the list of numbers passed as an individual argument to a function. Have a look at the function usage:


Calling a Variadic Function
Calling a Variadic Function | Source

In the first statement, a long variable is declared. In the next statement, a function GetMin is called with five parameters. In the third statement, the same function is called with eight parameters. Here, the function GetMin is Variadic as it accepts the different number of parameters. So when a function is a Variadic function, you can pass N number of parameters to it. In the above example, the first parameter tells, how many numbers of parameters passed to the function followed by actual parameters among which minimum should be picked. Here, the first parameter is Standard Parameter and next coming parameters are called “Parameter List”. Let us see how this function can be declared.

Have a look at the below picture:

Variadic Function Syntax Explanation
Variadic Function Syntax Explanation | Source

In the above picture, you are seeing a declaration of a variadic function. The function returns long data type and the name of the function is GetMin. The first parameter “nop” is called a standard parameter or named parameter. The three dots which can be also called as ellipsis signifies the variable argument list. That means, after passing the standard argument, you can pass ‘N’ number of arguments as shown in the first picture.

3. Va_start va_arg va_end

These macros are used to process the variable argument list passed to the function. Va_start will perform the population of va_list with the passed-in variable argument list. Va_arg will read the parameter from the current position in the list and advances the position to next one. Va_end is used to clear the va_list stating that the arguments are processed in the called function. Have a look at the below picture:

va_list and ...
va_list and ... | Source

Here, the ellipsis states the variable argument list and during the va_start call, the parameters in the placeholder of ellipsis are filled into the va_list.

4. Variadic Function – An Example

1) First, the required headers are included in the cpp file. The header file math.h is included to use the pow function which raises a given number to a power say x. To process the variadic argument list, the header file stdarg.h is included in the file. Below is the code change:

//1.0 Required includes
# include <stdio.h>
# include <stdarg.h>
# include <math.h>

2) The function Power_Summation is used to compute the summation by raising each number to a power of second passed-in parameter. In the below-given code, the first parameter “No_Params” tells how many variadic parameters are passed to the function. The second parameter is used to raise each number to power N. After raising the power of individual argument they are summed up.

The param_list used here holds the variable number of arguments passed to the function. This list is initialized by using the va_start macro. The first parameter expected by the macro is the va_list to hold the variable number of arguments. The second parameter passed to the macro is the last standard parameter, which is preceding the variadic arguments. In our case it is RaiseTo. Now the macro knows where the variadic parameter starts, as it knows where the standard parameters end.

A for loop is formed by making use of the first parameter passed to the function and in each iteration, the macro va-arg is used to extract the parameter one by one. A call will extract the variable in a current position and moves the extractor to next position in the variadic list (va_list). Note that va_arg expects the va_list as well as the data type of the parameter. In our case, we are going to pass float/double value as arguments and hence double is passed as the second parameter to the va_arg list. After extracting the parameter a cumulative summation is performed. The macro va_end is used to clear the list. The complete function is shown below:

//2.0 Function with variable argument list
double Power_Summation(long No_Params, int RaiseTo, ...)
{
  va_list param_list;
  va_start(param_list, RaiseTo);
  double sum = 0;

  for (long i=0; i<No_Params; i++)
  {
	  double base = va_arg(param_list, double);
	  sum = sum + pow(base, RaiseTo);
  }
  va_end(param_list);
  return sum;
}

In the Main() function, you can see the variadic function Power_Summation is called twice. When it is called for the first time, three variadic float parameters 1.0, 2.0, 3.0 are passed-in. And in the second case, four variadic parameters are passed. The first two parameters are standard parameters, which convey a number of parameters, Raise to a power respectively. Below is main program entry:

//3.0 Calling the Function
void main()
{
	double Total;
	Total = Power_Summation(3, 2, 1.0f, 2.0f, 3.0f);
	printf("Result 1: %f\r\n", Total);

	Total = Power_Summation(4, 3, 2.0f, 1.0f, 2.0f, 3.0f);
	printf("Result 2: %f\r\n", Total);
}

Output of the above program is shown below:


Program Output - Variable Number of Arg.
Program Output - Variable Number of Arg. | Source

© 2015 sirama

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.