Home > Backend Development > C++ > body text

How to use default parameters of C++ functions?

WBOY
Release: 2024-04-19 15:21:02
Original
767 people have browsed it

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

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

Output:

result1 = 10
result2 = 15
Copy after login

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!

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