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:

void funcName(type param = value) {
    // Code block
}

Example:

// Function definition
double pow(double base, int exp = 2){
    …
}

// Call using default values
cout << pow(3) << endl;

// Call overriding default value
cout << pow(3,3) << endl;

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:

void printTime(int hour = 12, int min = 00) {
    …
}

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.

printTime(); // Uses default value for hours and minutes
printTime(11); // Uses 11 for hours and default value for minutes
printTime(11, 15); // Uses 11 for hours and 15 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

void printTime(int hour, int min = 00) {
  // some code
}

Invalid: Default value is before non-default value

void printTime(int hour = 12, int min) {
  // some code
}

Last updated