Skip to content
Theory · Functions · lesson 9 of 13

Default arguments

When you order a coffee and do not name a size, the barista makes a medium. Every order still has a size, but most of the time it is the same one, so there is no need to repeat it. If you want a large, you say so yourself.

Functions also often have a parameter that almost always gets the same value. For example, power raises a number to a power, and most often that power is a square.

A value for when it is left out

A parameter can have a default argument: a value the compiler supplies when the call leaves that argument out. It is written in the parameter list after an = sign:

C++
#include <iostream>

int power(int base, int exp = 2) {
    int result = 1;
    for (int i = 0; i < exp; ++i) {
        result *= base;
    }
    return result;
}

int main() {
    std::cout << power(5) << ' ' << power(2, 10) << '\n';  // 25 1024
}

Let's walk through both calls:

  1. power(5): there is no second argument, and the compiler turns the call into power(5, 2). The loop multiplies result by 5 twice, which gives 25.
  2. power(2, 10): the second argument is given, and the default value is not needed. 2 to the tenth power is 1024.

The compiler fills in the value when it reads the call. There is only one function, and inside it exp always gets a value: either from the call or the default.

Not the same as overloading

Overloading can give similar behavior: write power(int base) and power(int base, int exp). But then there are two functions, and the body has to be repeated, or one has to call the other.

With a default argument there is one function, and it can be called with one argument or with two. If the versions must work differently, you need overloading. If only the parameter's value differs, a default argument is enough.

Common mistake

A default value is given to a parameter that is followed by a parameter without one:

C++
int power(int base = 2, int exp);  // ✗
TEXT
error: missing default argument on parameter 'exp'

This is a compiler error: after a parameter with a default value, every following parameter must have one too. Otherwise the call power(3) would not show which parameter gets 3. The call's arguments are matched to the parameters from left to right, so only the last ones can be left out.

Move the parameters with default values to the end of the list.

Key points

  • A default argument is a value the compiler supplies when the call does not pass one: int exp = 2.
  • The compiler turns the call power(5) into power(5, 2); there is still only one function.
  • Parameters with default values go at the end of the list: after such a parameter, every following one must have one too.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way