Title here
Summary here
Variadic functions can be called with any number of trailing arguments. For example, `fmt.Println` is a common variadic function.
Here's a function that will take an arbitrary number of `int`s as arguments.
```cpp
#include <iostream>
#include <vector>
void sum(std::initializer_list<int> nums) {
for (auto num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
int total = 0;
for (auto num : nums) {
total += num;
}
std::cout << total << std::endl;
}
int main() {
sum({1, 2});
sum({1, 2, 3});
std::vector<int> numbers = {1, 2, 3, 4};
sum({numbers.begin(), numbers.end()});
return 0;
}
Within the function, the type of nums
is equivalent to std::vector<int>
. We can call nums.size()
, iterate over it with a range-based for loop, etc.
Variadic functions can be called in the usual way with individual arguments.
sum({1, 2});
sum({1, 2, 3});
If you already have multiple args in a slice, apply them to a variadic function using a braced-init-list like this.
std::vector<int> nums = {1, 2, 3, 4};
sum({nums.begin(), nums.end()});
To run the program, put the code in a file named variadic_functions.cpp
and use the following commands to compile and run it:
$ g++ variadic_functions.cpp -o variadic_functions
$ ./variadic_functions
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10
Another key aspect of functions in C++ is their ability to form closures, which we’ll look at next.