Variadic arguments in C++

Hello, Learners here we will discuss Variadic arguments in C++. When a function is declared using Variadic arguments then a user can pass any number of arguments to this function while calling. Functions declared with Variadic arguments are called Variadic functions. So Variadic functions are those which take any number of arguments.

To declare a function as a Variadic function an ellipsis (…) is used as the last parameter.

The following functions are used to access the variadic arguments from the function body i.e. arguments passed by the user are accessed using following library facilities. These are :

  • va_start: It initializes a variable argument list. whenever va_start is invoked in any function that function must be invoked va_end before it returns the values.
  • va_list: It is used to hold the information needed by va_copy, va_end, va_arg, and va_start.
  • va_arg: This function is used to retrieve the next argument of a variadic function.
  • va_copy: This function is used to copy the variable argument list.
  • va_end: For ending the traversal of variadic function arguments va_end function is invoked.

All these facilities are available in the header <cstdarg>

C++ Implementation: Variadic arguments

#include <iostream>
#include <cstdarg> 

using namespace std;
 
void printArgs(const char* params...)
{
    va_list args;
    va_start(args, params);
 
    while (*params != '\0') {
        if (*params == 'd') {
            int i = va_arg(args, int);
            std::cout << i << '\n';
        } else if (*params == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            std::cout << static_cast<char>(c) << '\n';
        } else if (*params == 'f') {
            double d = va_arg(args, double);
            std::cout << d << '\n';
        } 
        ++params;
    }
 
    va_end(args);
}
 
// Driver function
int main()
{
    // while calling printArgs one can pass any number of arguments
    printArgs("dcff", 3, 'a', 1.999, 42.5); 
    return 0;
}
Output :3
a
1.999
42.5

Also read: Template Parameters and Template Arguments in C++

Leave a Reply

Your email address will not be published. Required fields are marked *