Home CPP Interview Questions

How does C++ support varying arguments to a function?

Varying arguments in C++:

C++ support function with varying argument list with help of 5 macros. They are: va_list, va_arg, va_start, va_end, va_copy.

One of the common techniques of calling function with varying arguments is to pass count of varying arguments as fixed, first argument to the function. So the 2 pre-requisites:
a. count of number of arguments received by function is required at run time to correctly extract each argument from the list.
b. Data type of each argument mus tbe known inside the function.

  1. va_list:
    va_list holds the arguments. So declare a list.
     
  2. va_start:
    va_start initializes this list.
     
  3. va_arg:
    va_arg takes list and a type as argument and returns next argument in the list of the specified type. It is always assumed that next argument will be of the specified type and no verification is done.
     
  4. va_end:
    va_end takes list as argument to do some internal clean up.


Example of function with varying arguments in C++:

void func(int count, ...)
{

va_list vlist;
va_start(vlist, count);

// do some processing like: int temp; temp=varg(vlist,int);

va_end(vlist);
}