typestar

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

  1. sep defaults to ", " and trailing to false; defaults must sit at the end of the parameter list.
  2. The body concatenates with sep and the ternary appends one more separator when trailing is set.
  3. The three calls pass two, three, and four arguments; missing ones fill in from the right.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Functions & lambdas, step 12 of 27 in Language basics.

← Previous Next →