C++ Programs Default Arguments
C++ allows you to specify a default argument for a function parameter. This means that you can define a default value for a parameter in the function declaration, which will be used if the caller does not specify a value for that parameter.
Syntax
return_type function_name(data_type parameter_name = default_value) {
// code
}
Example
#include <iostream>
using namespace std;
void printInt(int x = 10, int y = 20) {
cout << "x: " << x << ", y: " << y << endl;
}
int main() {
printInt(); // prints "x: 10, y: 20"
printInt(5); // prints "x: 5, y: 20"
printInt(5, 15); // prints "x: 5, y: 15"
return 0;
}
Output
x: 10, y: 20
x: 5, y: 20
x: 5, y: 15
Explanation
In the above example, we have defined a function called "printInt" which takes two integer parameters with default values of 10 and 20. This means that if the caller does not specify the values for these parameters, they will default to 10 and 20, respectively.
Use
Default arguments can be useful when you want to provide default values for function parameters without requiring the caller to provide them all the time. This can make the function more flexible and easier to use.
#include <iostream>
#include <string>
using namespace std;
void printMessage(string message = "Hello, World!") {
cout << message << endl;
}
int main() {
printMessage(); // prints "Hello, World!"
printMessage("Goodbye!"); // prints "Goodbye!"
return 0;
}
In the above example, we have defined a function called "printMessage" which takes a string parameter with a default value of "Hello, World!". This means that if the caller does not specify a value for the parameter, it will default to "Hello, World!".
Important Points
- Default arguments are specified in the function declaration.
- Any parameters with default values must come after any parameters without default values.
- Once a parameter has a default value, all subsequent parameters must also have default values.
- Default values can be constant expressions, global variables, or other function parameters.
Summary
In summary, default arguments in C++ allow you to specify default values for function parameters. This can make functions more flexible and easier to use, as the caller does not always have to specify every parameter value. Default arguments are specified in the function declaration and can be constant expressions, global variables, or other function parameters.