2.2.2 Default Values
A function default value is a value that can be used for a parameter if the calling statement does not pass an argument. If an argument is provided, the default value is ignored.
Basic Syntax
Function default values are assigned in the parameter list. After the parameter name, an assignment operator and value are used to denote a default value.
Basic Syntax:
Example:
In the example above, the first call only provides one parameter, which will be used as the base. Since the second parameter is not provided, the value of the exp
parameter will be 2.
For the second call, a value is provided for the exp
parameter, so the default value is ignored and exp
will be equal to 3 for that call.
Multiple Default Values
In C++, you can have multiple default values, for example:
There are a couple of things to keep in mind though. First, if you have a function that has multiple default values, the values are matched from left to right, so you can only leave off arguments to the right.
This means that in the example above, it is not possible to use a default value for hours
without using the default value for minutes
.
Second, regardless of how many default values you use, the default values need to be your last parameters.
Valid: Default value is after non-default value
Invalid: Default value is before non-default value
Last updated