Home > Article > Backend Development > How to define and call variadic functions in C++?
In C, use... (ellipsis) to define a variable parameter function, allowing the function to accept any number of parameters; when calling, just treat it as a fixed parameter function.
#How to define and call variadic functions in C?
Variadic functions (also known as variadic functions) allow functions to accept any number of parameters. The C standard library contains a series of variadic functions, such as printf()
and scanf()
. You can also define your own variadic functions.
Define a variadic function
To define a variadic function, use the syntax ...
(ellipsis). It means that the function can take any number of parameters. For example:
#include <iostream> #include <cstdarg> // 包含 va_list 和相关的宏 void print_numbers(int count, ...) { va_list args; va_start(args, count); // 初始化 va_list 对象 // 遍历可变参数 for (int i = 0; i < count; i++) { int num = va_arg(args, int); // 获取下一个 int 类型的参数 std::cout << num << " "; } va_end(args); // 清理 va_list 对象 }
Note that ...
must be placed after all fixed parameter definitions.
Calling a variadic function
To call a variadic function, simply treat it as another function with a fixed number of arguments. For example:
print_numbers(3, 1, 2, 3);
This function will print out 1 2 3
.
Practical case
The following example demonstrates how to define and call a variable parameter function:
#include <iostream> void print_max(int count, ...) { va_list args; va_start(args, count); // 保存最大值 int max = INT_MIN; // 获取并比较可变参数 for (int i = 0; i < count; i++) { int num = va_arg(args, int); if (num > max) { max = num; } } va_end(args); // 打印最大值 std::cout << "最大值:" << max << std::endl; } int main() { print_max(3, 1, 2, 3); print_max(5, 3, 5, 2, 1, 7); return 0; }
Output:
最大值:3 最大值:7
The above is the detailed content of How to define and call variadic functions in C++?. For more information, please follow other related articles on the PHP Chinese website!