Home  >  Article  >  Backend Development  >  How to use default parameters of C++ functions?

How to use default parameters of C++ functions?

WBOY
WBOYOriginal
2024-04-19 15:21:02714browse

Default parameters allow functions to specify default values ​​when called, simplifying code and improving maintainability. The syntax of default parameters is: type function_name(parameter_list, type parameter_name = default_value). Among them, type is the parameter type, parameter_name is the parameter name, and default_value is the default value. In the example, the add function has two parameters, of which num2 has a default value of 0. When calling the function, you can specify only num1 and num2 will use the default value, or specify both num1 and num2.

C++ 函数的默认参数的使用方法是什么?

#Default parameter usage of C function

Default parameter is a parameter that allows a function to specify a default value when it is called. This is useful to avoid repeatedly specifying common values, making the code cleaner and easier to maintain.

Syntax

The syntax of the default parameter is as follows:

type function_name(parameter_list, type parameter_name = default_value);

Where:

  • type is the type of the parameter.
  • parameter_name is the name of the parameter.
  • default_value is the default value of the parameter.

Practical case

The following example shows how to create and use a function with default parameters:

#include <iostream>

using namespace std;

// 具有两个参数的函数,其中第二个参数具有默认值
int add(int num1, int num2 = 0) {
  return num1 + num2;
}

int main() {
  // 调用函数,仅指定第一个参数
  int result1 = add(10);  // 使用默认值 0

  // 调用函数,指定两个参数
  int result2 = add(10, 5);

  // 输出结果
  cout << "result1 = " << result1 << endl;
  cout << "result2 = " << result2 << endl;

  return 0;
}

Output:

result1 = 10
result2 = 15

In this example , the add function has two parameters: num1 and num2, where the default value of num2 is 0 . When calling the function with add(10), specifying only the value of num1, num2 will use its default value of 0. And when the function is called using add(10, 5), the values ​​of num1 and num2 will be specified.

The above is the detailed content of How to use default 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