Default Parameter Values
In the previous exercise, you saw that a call with a missing argument doesn't compile. But often there's a value that fits most cases, and we want to pass a different one only now and then. For example, most people order a medium coffee. For such cases, a parameter can have a default value: after the name of the parameter, write = and the value:
#include <iostream>
#include <string>
void orderCoffee(std::string drink, std::string size = "medium") {
std::cout << drink << ", size: " << size << std::endl;
}
int main() {
orderCoffee("Latte", "large");
orderCoffee("Espresso");
}This program prints:
Latte, size: large
Espresso, size: mediumWhen the call passes an argument for size, the function uses it. When it doesn't, the function uses the default value "medium". Without the default value, the second call wouldn't compile, because it would be missing an argument.
Arguments go into parameters in order, so parameters with default values belong at the end. Then you can leave out the last arguments, and the ones you pass still get into the right parameters. C++ doesn't even allow a parameter without a default value after a parameter with one:
void orderCoffee(std::string size = "medium", std::string drink) {Such a program doesn't compile. The error error: missing default argument on parameter 'drink' says that the parameter drink is missing a default value: once a parameter has a default value, all the parameters after it must have one too.
Instructions
- 1
Our shop gives most prices in euros, so the last call in
mainpasses only the price. That's why the program doesn't compile. Give the parametercurrencythe default value"EUR". The program then prints three prices, and the last one isPrice: 80 EUR. - 2
Below the function
printPrice, create a functionprintLinewith two parameters:lengthof typeintandsymbolof typecharwith the default value'-'. The function printssymbolas many times aslengthsays, all on one line: in aforloop, print onlysymbol, and end the line after the loop. - 3
At the end of
main, callprintLine(10)and thenprintLine(5, '*'). Below the prices, the program prints a line of ten dashes and, below it, five stars:---------- *****