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

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

WBOY
WBOYOriginal
2024-04-19 16:03:01859browse

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, ...);

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;
}

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);

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

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

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!

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