Variable Number of Arguments in C++



Sometimes, you may come across a scenario where you want to have a function that can take a variable number of arguments, i.e., parameters, instead of a predefined number of parameters. The C/C++ programming language provides a solution for this scenario, and you are allowed to define a function that can accept a variable number of parameters based on your requirement. Following are the ways to use variable number of arguments ?

C-style Variadic Functions (with stdarg.h)

C-style variadic functions in C++ use stdarg.h macros like va_start, va_arg, and va_end to handle a variable number of arguments at runtime.

int func(int, ... ) { . . . } int main() { func(1, 2, 3); func(1, 2, 3, 4); }

It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement variable number of arguments.

Variadic Templates (Modern C++)

Variadic templates in modern C++ allow functions or classes to accept an arbitrary number of template arguments. They use recursive template expansion to process each argument in a type-safe manner.

template void print(T t) { cout << t << " "; } template void print(T t, Args... args) { cout << t << " "; print(args...); }

Example of Variable Number of Arguments

Following is the simple function which can take the variable number of parameters and return their average:

Open Compiler
#include <iostream> #include <cstdarg> using namespace std; double average(int num,...) { va_list valist; double sum = 0.0; int i; va_start(valist, num); //initialize valist for num number of arguments for (i = 0; i < num; i++) { //access all the arguments assigned to valist sum += va_arg(valist, int); } va_end(valist); //clean memory reserved for valist return sum/num; } int main() { cout << "Average of 2, 3, 4, 5 = "<< average(4, 2,3,4,5) << endl; cout << "Average of 5, 10, 15 = "<< average(3, 5,10,15)<< endl; }

Following is the output of the above code:

Average of 2, 3, 4, 5 = 3.5
Average of 5, 10, 15 = 10

Example of Variable Number of Arguments Using Variadic Template

This is simple example of variadic templates, function recursively prints any number of arguments of different types:

Open Compiler
#include <iostream> using namespace std; template<typename T> void print(T t) { cout << t << endl; } template<typename T, typename... Args> void print(T t, Args... args) { cout << t <<" "; print(args...); } int main() { print(1, 2.5, "hello", 'A'); return 0; }

The following is the output of the above code:

1 2.5 hello A
Updated on: 2025-05-28T16:51:15+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements