Variadic Function Arguments

Variadic functions are those that accept a variable number of arguments.

Python

In Python, this is done using the *args and **kwargs.

def variadic_function(*args):
    for arg in args:
        print(arg)
 
variadic_function(1, 2, 3)
def variadic_function(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)
 
variadic_function(1, 2, 3, name="Alice", age=30)

The kwargs is used for those with keyword arguments

Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 30}

C++

In C++, we use a Variadic Templates. Note that this different that function overloading, which is defining the function multiples times depending on signature.

template <typename... Args>
void Hello(Args... args) {
    (std::cout << ... << args) << std::endl;  // Fold expression to print each argument
}
  • This is available since C++17

On C++11, you would do this

template <typename T, typename... Args>
void Hello(T first, Args... args) {
    std::cout << first << std::endl;  // Print the first argument
    Hello(args...);                   // Recursively call with remaining arguments
}
 
  • It recursively calls it on each argument

Thereā€™s another way, which I found out through chatgpt which is to use <cstdarg>

#include <iostream>
#include <cstdarg>
 
void variadicFunction(int num, ...) {
    va_list args;
    va_start(args, num);
 
    for (int i = 0; i < num; ++i) {
        int value = va_arg(args, int);  // Get next argument, specifying the type
        std::cout << value << std::endl;
    }
 
    va_end(args);
}
 
int main() {
    variadicFunction(3, 10, 20, 30);  // First argument is the count of subsequent arguments
    return 0;
}