Default arguments in C++
Trailing parameters get fallback values, so one join serves three call shapes.
#include <string>
// Defaults fill in from the right; callers pass only what differs.
std::string join(const std::string& a, const std::string& b,
const std::string& sep = ", ", bool trailing = false) {
std::string out = a + sep + b;
return trailing ? out + sep : out;
}
std::string join_demo() {
return join("salt", "pepper") + join("x", "y", " | ") +
join("a", "b", ";", true);
}
How it works
sepdefaults to", "andtrailingtofalse; defaults must sit at the end of the parameter list.- The body concatenates with
sepand the ternary appends one more separator whentrailingis set. - The three calls pass two, three, and four arguments; missing ones fill in from the right.
Keywords and builtins used here
boolconstfalsereturntrue
The run, in numbers
- Lines
- 13
- Characters to type
- 383
- Tokens
- 119
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 89 seconds.
Step 3 of 3 in Functions & lambdas, step 12 of 27 in Language basics.