C++ Function with Default Parameter Values

In C++, functions can have default parameter values. A default value is assigned to a parameter in the function declaration, making the parameter optional during a function call. If no argument is provided for a parameter with a default value, the default value is used.

Syntax

The following is the syntax to write a function with default values for parameters.

</>
Copy
return_type function_name(parameter_type1 parameter_name1 = default_value1, 
                            parameter_type2 parameter_name2 = default_value2, ... ) {
    // Function body
}

Explanation:
return_type: Specifies the type of value the function returns. Use void if the function does not return anything.
function_name: The name of the function, following C++ naming conventions.
parameter_name = default_value: Specifies a default value for the parameter. If no argument is provided for this parameter during the function call, the default value is used.


Examples for Function with Default Parameter Values

Example 1: Greeting with a Default Name

In this example, we will write a function with a parameter specified with a default value.

</>
Copy
#include <iostream>
using namespace std;

void greet(string name = "Guest") {
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet(); // Uses the default value
    greet("Alice"); // Overrides the default value
    return 0;
}
Hello, Guest!
Hello, Alice!

Explanation: The greet function has a parameter name with a default value of "Guest". When no argument is passed, the function uses the default value. If an argument is provided, it overrides the default value.

Example 2: Calculating the Area of a Rectangle

In this example, we will write a function calculateArea with two parameters, of which the second parameter has a default value.

</>
Copy
#include <iostream>
using namespace std;

int calculateArea(int length, int width = 10) {
    return length * width;
}

int main() {
    cout << "Area (default width): " << calculateArea(5) << endl; // Uses default width
    cout << "Area (custom width): " << calculateArea(5, 20) << endl; // Overrides default width
    return 0;
}

Output:

Area (default width): 50
Area (custom width): 100

Explanation: The calculateArea function has a default value of 10 for the parameter width. When only the length is provided, the default width is used. If both length and width are provided, the default value is overridden.