Home > Backend Development > C++ > How to define and call variadic functions in C++?

How to define and call variadic functions in C++?

WBOY
Release: 2024-04-12 21:03:02
Original
965 people have browsed it

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.

C++ 中如何定义和调用可变参数函数?

#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 对象
}
Copy after login

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

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

Output:

最大值:3
最大值:7
Copy after login

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!

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