## Tuesday, January 20, 2015

### C Function with Variable Number of Arguments

One usually need to implement a function where the number of arguments (parameters) is not known, or is not constant, when the function is written. Just like the printf function. The following example shows that in terms of code:

int f(int, ... ) {
.
.
.
}

int g() {
f(1,2,3);
f(1,2);
}

Let's consider a simple example, we need to implement a function GetSum that calculates the summation of any number of integers.
So, such function takes variable number of arguments.
The first one is Size: the number of integers to calculate the summation for.
Then it takes each integer of the numbers to be added as a separate parameter.

You can call it to calculate the summation of two numbers (4+30), like :
GetSum(2, 4, 30); /* returns 34 */

Or to calculate the summation of 5 numbers (7+10+1+15+3), like :
GetSum(5, 7, 10, 1, 15, 3); /* returns 36 */

The implementation of GetSum is as follows. The comments describe everything:

#include <stdarg.h>
int GetSum(int Size...)
{
int Sum = 0.0;

// 1- Create Variable List
va_list variable_list;

// 2- Initialize variable_list to retrieve data
//      starting from the address of the parameter Size
va_start(variable_list, Size);

// 3- Access all the arguments assigned to variable_list
for (int Index = 0; Index < Size; Index++{
Sum += va_arg(variable_list, int);
}

// 4- Clean memory reserved for variable_list
va_end(variable_list);

return Sum;
}