C++ Default Argument Values
In C++, you can provide default argument values for a function's parameters, which allows you to call the function with fewer arguments than there are parameters.
Here's an example of a function with default argument values:
int multiply(int a, int b = 1) {
return a * b;
}Soruce:www.theitroad.comIn this function, a is a required parameter, and b has a default value of 1. This means that if you call the function with only one argument, b will automatically be set to 1.
int result1 = multiply(3, 4); // result1 is 12 int result2 = multiply(5); // result2 is 5, because b is set to 1 by default
In the first example, a is set to 3 and b is set to 4. In the second example, a is set to 5 and b is set to the default value of 1.
Note that default arguments can only be specified in the function declaration, not in the function definition. If you provide a default value in the declaration, you do not need to provide it again in the definition.
// Function declaration with default argument
int multiply(int a, int b = 1);
// Function definition
int multiply(int a, int b) {
return a * b;
}
When you call a function with default argument values, you can still specify a value for the parameter with the default value, if you want to override the default.
int result1 = multiply(3); // result1 is 3, because b is set to 1 by default int result2 = multiply(5, 2); // result2 is 10, because b is set to 2 explicitly
