Functions
C++ Default Arguments
Default Arguments
C++ default arguments provide fallback values in functions.
Understanding Default Arguments in C++
In C++, default arguments allow you to specify default values for one or more parameters of a function. This feature helps you call a function without explicitly passing all the arguments, making the code more flexible and easier to read.
Defining Default Arguments
To define default arguments, you simply provide a value in the function declaration. These default values are used by the function if you do not provide your own values when calling the function.
In the example above, the function printInfo
has a default argument for age
. If age
is not specified when calling printInfo
, it defaults to 30.
Using Default Arguments
When calling a function with default arguments, you can choose to omit the arguments for which defaults are provided. If you supply an argument, it overrides the default value.
In the main
function, printInfo("Alice")
uses the default value for age
, while printInfo("Bob", 25)
overrides it.
Rules and Best Practices
- Order Matters: Default arguments must be the trailing parameters in a function declaration.
- Function Declaration: Default argument values must be specified in the function declaration, not in the definition.
- Multiple Defaults: You can have multiple default arguments, but all should be at the end of the parameter list.
In the correct usage example, delimiter
and repeat
are trailing parameters with default values. The incorrect example places a default argument before a non-default argument, which is not allowed.
Functions
- Functions
- Function Overloading
- Default Arguments
- Inline Functions
- Lambda Expressions
- Function Pointers
- Previous
- Function Overloading
- Next
- Inline Functions