Home > Backend Development > C++ > body text

How to use variable length parameters of C++ functions?

王林
Release: 2024-04-19 12:18:02
Original
769 people have browsed it

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++ 函数的变长参数的使用方式是什么?

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);
Copy after login

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);
Copy after login

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 
#include 

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;
}
Copy after login

Output

数字列表和为:15
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!