Home  >  Article  >  Backend Development  >  Detailed explanation of default parameters and variable parameters of C++ functions

Detailed explanation of default parameters and variable parameters of C++ functions

WBOY
WBOYOriginal
2024-04-19 16:18:02730browse

C Default parameters allow setting default values ​​for function parameters, while in variadic parameters, any number of parameters can be provided to the function. Specifically: Default parameters: Allows specifying default values ​​for parameters when the function is declared, and using the default value if no value is provided when calling. Variable parameters: Use... to indicate that the function can accept any number of parameters and obtain the parameters through va_arg.

C++ 函数的默认参数和可变参数详解

#Detailed explanation of default parameters and variable parameters of C function

Default parameters

Default parameters allow us to specify parameters when the function is declared a default value. This way, when the function is called, if no value is provided for the parameter, the default value is used.

Syntax:

return_type function_name(parameter_type1 parameter_name1 = default_value1,
                       parameter_type2 parameter_name2 = default_value2,
                       ...);

Practical case:

Consider the following function, which has a default max_size Parameters:

int get_max_size(int max_size = 100) {
  // 函数体
  return max_size;
}

This function can be called as follows:

int size1 = get_max_size(); // 使用默认值 100
int size2 = get_max_size(50); // 使用给定值 50

Variadic parameters

Variadic parameters allow us to provide any number of parameters to the function. In function declarations, variable parameters are represented using ....

Syntax:

return_type function_name(parameter_type1 parameter_name1,
                       parameter_type2 parameter_name2,
                       ...,
                       parameter_typeN ...parameter_nameN);

Practical example:

Consider the following function, which calculates the sum of any number of numbers:

int sum(int num, ...) {
  int sum = num;
  
  va_list args;
  va_start(args, num);
  
  while (true) {
    int n = va_arg(args, int);  // 获取下一个参数
    if (n == 0) {
      break;
    }
    sum += n;
  }
  
  va_end(args);
  return sum;
}

This The function can be called as follows:

int sum1 = sum(1, 2, 3, 4, 5); // 求和 1 + 2 + 3 + 4 + 5 = 15
int sum2 = sum(10, 20, 30, 0); // 求和 10 + 20 + 30 = 60

The above is the detailed content of Detailed explanation of default parameters and variable parameters of C++ functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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