Step 5 of 5
Default arguments
A parameter can have a default value that's used when the caller leaves the argument out:
#include <iostream>
#include <string>
std::string repeat(const std::string& s, int times = 2, const std::string& sep = " ") {
std::string out;
for (int i = 0; i < times; i++) {
if (i > 0) out += sep;
out += s;
}
return out;
}
int main() {
std::cout << repeat("go") << "\n";
std::cout << repeat("go", 3) << "\n";
std::cout << repeat("go", 3, "-") << "\n";
}
go go
go go go
go-go-go
Rules
- Defaults must be at the end of the parameter list. Once one parameter has a default, all the ones after it need defaults too, because arguments are matched left to right: you can't skip the middle one.
- Put the default in the declaration (usually the header), not repeated in the definition.
- Defaults are filled in at the call site, so
repeat("go")is compiled asrepeat("go", 2, " ").
Defaults are a lightweight alternative to writing several overloads when the extra parameters are just options with sensible standard values.
Building a string
std::string out; starts empty, and += appends. For padding, std::string(n, c) creates a string of n copies of the character c, which you can then join with +. Always handle the case where nothing needs to be added (the input is already long enough).
Your turn: write std::string pad(const std::string& s, int width, char fill = ' ') that adds fill characters on the left until the string is width long. Strings already that long are returned unchanged.