Home > Backend Development > C++ > How to set the default values ​​of parameters of C++ functions?

How to set the default values ​​of parameters of C++ functions?

WBOY
Release: 2024-04-19 16:03:01
Original
890 people have browsed it

In C it is possible to set default values ​​for function parameters, so that default values ​​are used when no parameters are passed, by specifying an equal sign (=) and the default value after the parameter type. In practice, if the function does not pass parameters, the default value will be used, but actual values ​​can also be passed.

C++ 函数的参数的默认值如何设置?

C Default value settings for function parameters

In C, you can set default values ​​for function parameters so that when the function is called Default values ​​are used when no parameters are passed. This is accomplished by specifying an equal sign (=) and a default value after the parameter type.

Syntax:

void function(int param1 = default_value, int param2 = default_value, ...);
Copy after login

Among them:

  • param1, param2: function parameters
  • default_value: The default value of the parameter

Practical case:

Consider a calculation of the sum of two numbers Function:

int sum(int num1, int num2 = 0) {
  return num1 + num2;
}
Copy after login

In this example, the default value of the num2 parameter is set to 0. This means that when calling the function without passing the num2 parameter, the function will use the default value 0.

Usage:

When calling a function, you can use the default value or pass the actual value:

  • Use the default value:
int result1 = sum(10);
Copy after login

This will calculate the sum of 10 and 0, resulting in 10.

  • Pass the actual value:
int result2 = sum(10, 5);
Copy after login

This will calculate the sum of 10 and 5, The result is 15.

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