Function arguments – c++

There are sometimes that you want to pass more than a defined number of parameters to a function (arguments). Of course you can pass a array of parameters or just use a inbuilt stdarg.h library. This allows you to pass allot of arguments into a function, but without defining them at compile time.

For example if you want to add up a list of numbers and run time, but do not know how many to pass at the compile time then you define the function method as

int sumvalues(int numbersToBePassed, ...);

The important part is the “…”, you have to always pass in the first parameter at least, because at run time this parameter will tell the function how many additional parts to the function there will be.

Then to setup the argument list, you use the c++ library stdarg.h and this will include the function/methods that will allow this to happen.

To start with you will need to setup the argument list,

va_list args

This will setup the variable args to contain the list of additional arguments passed, then to setup where to start to pull arguments from, e.g. where the last parameter named at compile time will know, if the parameter list is like

int sumedvalues(int value1, int value2, int additionalValues, ...)

then the additionalValues is the last parameter that the compile time will know about, so to setup the pointer to the next parameter for the args variable

// for the above example
va_start(args, additionValues);
//for the code example
va_start(args, numbersToBePassed);

to pull out a argument you just need to use the va_arg function, its parameters are

va_arg(va_list, type);

where the va_list is the args variable and the type is the type that you want back, e.g. int or float.

To complete the argument list you need to end the argument pull by

va_end(va_list)

where again the va_list would be args in this example.

Here is some code that will demo the above as well.

#include <iostream>
#include <stdarg.h>
 
using namespace std;
 
int sumvalues(int numbersToBePassed, ...)
{
  int sumd =0;
  va_list args;
  va_start(args,numbersToBePassed);
 
  for (int i =0; i < numbersToBePassed; i++)
  {
    sumd +=va_arg(args,int);
  }
  va_end(args);
  return sumd;
}
 
int main()
{
  cout << "Add the values 5 4 3 5 together = " << sumvalues(4, 5,4,3,5) << endl;
  return 0;
}

With the output being

Add the values 5 4 3 5 together = 17