Home > Article > Backend Development > How to use variable length parameters of C++ functions?
Variable parameter functions in C allow receiving a variable number of parameters. The syntax is: returntype function_name(type1 arg1, type2 arg2, ..., typen argn);. When calling a variable-length parameter function, use the form function_name(arg1, arg2, ..., argn);, where arg1 to argn are the actual parameters passed. As shown in the actual case, the function sum that calculates the sum of a list of numbers uses va_list to traverse and accumulate variable-length parameters to achieve the function of dynamically obtaining parameters and calculating.
C Variable-length parameters of the function
Variable parameters allow the function to receive a variable number of parameters. In C, use the ...
(ellipsis) syntax to specify variable-length arguments.
Syntax
returntype function_name(type1 arg1, type2 arg2, ..., typen argn);
Among them, returntype
is the return value type of the function, arg1
, arg2
, ..., argn
is the function parameter list, ...
represents variable length parameters.
Calling
When calling a variable-length parameter function, you can use the following form:
function_name(arg1, arg2, ..., argn);
where, arg1
, arg2
, ..., argn
are the parameters actually passed to the function.
Practical case
Here is an example of a function that calculates the sum of a given list of numbers:
#include <iostream> #include <stdarg.h> using namespace std; // 计算数字列表和的函数 int sum(int num, ...) { va_list args; int sum = num; // 获取变长参数 va_start(args, num); // 遍历变长参数并累加 while (int arg = va_arg(args, int)) { sum += arg; } // 清理变长参数 va_end(args); return sum; } int main() { // 调用函数计算数字列表和 cout << "数字列表和为:" << sum(1, 2, 3, 4, 5) << endl; return 0; }
Output
数字列表和为:15
The above is the detailed content of How to use variable length parameters of C++ functions?. For more information, please follow other related articles on the PHP Chinese website!