# Function parameters and default arguments

> A function's type is built from its adjusted parameter types, so arrays become pointers and top-level const disappears, while default arguments stay outside the type and are bound to the declaration a call happens to see.

- **Source:** C++ Atlas (https://cppatlas.com/topics/function-parameters-and-default-arguments)
- **Track:** Expressions and functions
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.fct] (https://eel.is/c++draft/dcl.fct), [dcl.fct.default] (https://eel.is/c++draft/dcl.fct.default), [dcl.ambig.res] (https://eel.is/c++draft/dcl.ambig.res), [expr.call] (https://eel.is/c++draft/expr.call), [conv.prom] (https://eel.is/c++draft/conv.prom), [conv.fpprom] (https://eel.is/c++draft/conv.fpprom), [cstdarg.syn] (https://eel.is/c++draft/cstdarg.syn), [except.spec] (https://eel.is/c++draft/except.spec), [conv.fctptr] (https://eel.is/c++draft/conv.fctptr), [over.over] (https://eel.is/c++draft/over.over), [class.mem] (https://eel.is/c++draft/class.mem)
- **cppreference links:** [Function declaration](https://en.cppreference.com/w/cpp/language/function), [Default arguments](https://en.cppreference.com/w/cpp/language/default_arguments), [Variadic arguments](https://en.cppreference.com/w/cpp/language/variadic_arguments), [Pointer declaration (pointers to functions)](https://en.cppreference.com/w/cpp/language/pointer), [Address of an overloaded function](https://en.cppreference.com/w/cpp/language/overloaded_address)
- **Prerequisites:** implicit-conversions, initialization-forms, inheritance-and-virtual-functions

## The one idea

A function declaration does two separate jobs. It fixes the function's **type**, which is the return type, the parameter-type-list, and since C++17 whether it is `noexcept`. And it may attach **default arguments**, which are not part of the type at all but a property of that particular declaration.

Almost every surprise in this area comes from mixing the two up. The type is computed after the compiler has rewritten your parameter declarations, so what you wrote is not always what the function takes. Default arguments are substituted by the caller, at compile time, using whatever declaration the call can see and whatever static type the call goes through.

> **Mental model.** The type decides which function you have and what pointers to it look like. Default arguments are a caller-side convenience, pasted in by the compiler from the declaration in view.

## Parameter types are adjusted

[dcl.fct] rewrites each parameter type before the function type is formed. A parameter of type "array of `T`" becomes "pointer to `T`". A parameter of function type becomes a pointer to function. Then top-level `const` and `volatile` are dropped. The resulting list is the parameter-type-list, and it alone determines whether two declarations name the same function.

```cpp
#include <type_traits>

void f(const int a[10]);   // the 10 is ignored; the element const is kept
void f(const int* a);      // redeclares the same function

void g(const int n);       // top-level const is dropped from the type
void g(int n) { n = 1; }   // the definition: n is modifiable here

void h(int callback(int)); // a pointer to function, as if int (*callback)(int)

static_assert(std::is_same_v<decltype(f), void(const int*)>);
static_assert(std::is_same_v<decltype(g), void(int)>);
```

Only the outermost array bound is lost, so `int m[][4]` becomes `int (*)[4]` and the inner bound is part of the type. A reference to an array is not adjusted, which is how `template <std::size_t N> void f(int (&a)[N])` recovers the length. Top-level `const` on a parameter in a definition is legal and only affects the body; repeating it in the header is noise. This also means `sizeof` on an array parameter yields the size of a pointer, which compilers warn about.

## Default arguments are bound at the declaration

A default argument is an expression stored with the declaration. Its names are looked up and bound where the declaration appears, but the expression is evaluated anew at every call that uses it.

```cpp
#include <cstdio>

int level = 1;
void report(int v = level) { std::printf("%d\n", v); }

void demo() {
  int level = 2;   // ignored: the default was bound to ::level
  (void)level;
  ::level = 3;
  report();        // prints 3: ::level is read at the call
}
```

Because the expression is evaluated in the caller's context but bound in the declaration's, the standard restricts what it may name. A default argument may not use `this` or a local variable, and another parameter may not appear in it as a potentially-evaluated expression. That last rule still allows unevaluated uses, so `void f(int a, int b = sizeof(a));` is valid.

```cpp
// void f(int a, int b = a);   // ill-formed: parameter used in a default argument
```

Member functions have one extra freedom. A default argument of a member function declared inside a class is a complete-class context, like a member function body, so it is parsed only after the whole class has been seen and may name members declared later. It still may not use a non-static data member in an evaluated way, because that would need `this`.

```cpp
struct Buffer {
  void resize(int n = default_size);   // OK: default_size is declared below
  static constexpr int default_size = 16;
  int width = 4;
  // void grow(int n = width);         // ill-formed: would need this
  void grow(int n = sizeof(width));    // OK: unevaluated operand
};
```

### Accumulating across declarations

For a non-template function, later declarations in the same scope may add default arguments, but only for parameters to the right of which every parameter already has one, and they may never repeat a default, not even with the same value.

```cpp
#include <cstdio>

void f(int, int);
void f(int, int = 2);    // adds a default for the second parameter
void f(int = 1, int);    // now the first may have one too
// void f(int, int = 2); // ill-formed: redefines a default argument
void f(int a, int b) { std::printf("%d %d\n", a, b); }

void demo() { f(); }     // prints 1 2
```

A declaration in a different scope starts a fresh set. A block-scope declaration of the same function can give it entirely different defaults, visible only in that block. The standard allows it; style guides do not.

> **Standardese.** [dcl.fct.default] says that for non-template functions, default arguments can be added in later declarations of a function in the same scope, and that declarations in different scopes have completely distinct sets of default arguments. Member functions of class templates are stricter: their default arguments must appear on the initial declaration inside the class template.

## Default arguments and virtual functions

Because the caller substitutes the default, it uses the declaration found through the static type of the call. A virtual call still dispatches to the final overrider, but it receives the default argument of the function named by the static type.

```cpp
#include <cstdio>

struct Base {
  virtual void show(int n = 1) const { std::printf("Base %d\n", n); }
  virtual ~Base() = default;
};
struct Derived : Base {
  void show(int n = 2) const override { std::printf("Derived %d\n", n); }
};

void demo() {
  Derived d;
  const Base& b = d;
  b.show();   // prints Derived 1: body from Derived, default from Base
  d.show();   // prints Derived 2
}
```

> **Pitfall.** Never give an override a different default argument. Either repeat the base default or, better, remove defaults from virtual functions and provide a non-virtual wrapper that supplies them.

The same reasoning explains why default arguments vanish through pointers. A pointer to function has only a type, and the type has no defaults, so `void (*p)(int) = report;` must be called with an argument. `std::function` behaves the same way.

## Variadic functions and default argument promotions

A C-style variadic function declares `...` after its named parameters. Arguments that match the ellipsis have no parameter type to convert to, so [expr.call] applies a fixed set of conversions instead: lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions, then the **default argument promotions**. Integer types narrower than `int`, including `bool`, `char` and `short`, are promoted to `int` or `unsigned int`, unscoped enumerations are promoted, and `float` becomes `double`. `std::nullptr_t` becomes `void*`.

```cpp
#include <cstdarg>

double sum(int n, ...) {
  va_list ap;
  va_start(ap, n);
  double s = 0;
  for (int i = 0; i < n; ++i) {
    s += va_arg(ap, double);   // must name the promoted type
  }
  va_end(ap);
  return s;
}

double demo() { float f = 1.5f; return sum(2, f, 2.5); }   // 4: f arrived as double
```

Asking `va_arg` for `float`, `char` or `short` is undefined behaviour, because no argument of that type can arrive. Passing a scoped enumeration, or a class type with a non-trivial copy constructor, move constructor or destructor, through `...` is conditionally-supported with implementation-defined semantics, so do not rely on it. C++ also allows a function with only an ellipsis, `void f(...)`, which overload resolution ranks below every other conversion; that is why it serves as a catch-all in detection idioms. C++26 deprecates writing the ellipsis without a preceding comma, as in `void f(int...)`, because it is easily confused with a parameter pack. Variadic templates, covered in variadic-templates-and-fold-expressions, are the type-safe replacement.

## Declarations that look like objects

[dcl.ambig.res] resolves an ambiguity between a declaration and an expression statement in favour of the declaration. When an initializer in parentheses could be read as a parameter list, it is.

```cpp
struct Timer {};
struct Widget { explicit Widget(Timer) {} int size() const { return 1; } };

void demo() {
  Widget w(Timer());   // declares a function w taking a pointer to function returning Timer
  // w.size();         // ill-formed: w is a function, not an object
  Widget v{Timer{}};   // braces cannot form a parameter list: an object
  (void)v;
}
```

The same rule makes `std::string s();` a function declaration and `int x(int(y));` a declaration of `x` taking an `int` named `y`. Braced initialization, an extra pair of parentheses around the argument, or `=` all force the object reading. The broader choice between initialization syntaxes is the subject of initialization-forms.

## The function type: noexcept, qualifiers and pointers

Since C++17, `noexcept` is part of the function type. A pointer to a `noexcept` function converts implicitly to a pointer to a potentially-throwing one, but not the other way, because that would promise something the function does not. You still cannot overload on `noexcept` alone, and every declaration of a function must agree on its exception specification. The noexcept topic covers what the specifier promises at run time.

```cpp
void may_throw() {}
void no_throw() noexcept {}

void (*p)() = no_throw;               // OK: drops the guarantee
// void (*q)() noexcept = may_throw;  // ill-formed: would add a guarantee
```

For member functions, cv-qualifiers and ref-qualifiers are also part of the type, as described in member-functions-and-this.

A function name converts to a pointer to function, so `p = f` and `p = &f` mean the same thing, and calling through `p(1)`, `(*p)(1)` or even `(**p)(1)` all work, because dereferencing gives back a function lvalue that decays again. When the name is overloaded, the target type chooses: `void (*ph)(double) = h;` selects `h(double)` from the set, under the rules of [over.over]. Since C++20, the standard library says that taking the address of most standard library functions is unspecified or ill-formed, so pass a lambda instead of `&std::toupper`.

## What to remember

- The function type is formed from adjusted parameters: arrays and functions become pointers, and top-level cv-qualifiers are dropped.
- Only the outermost array bound is lost; references to arrays keep their bound.
- Default arguments are not part of the type: they are bound by name at the declaration and evaluated at each call.
- A default argument cannot use `this`, locals, or other parameters in evaluated contexts.
- Later declarations in the same scope may add defaults right to left but never repeat one; other scopes get a fresh set.
- A virtual call uses the default from the static type and the body from the dynamic type.
- Arguments passed to `...` undergo default argument promotions; `va_arg` must name the promoted type.
- If something can be read as a function declaration, it is; braces avoid the most vexing parse.
- Since C++17 `noexcept` is in the type, and pointers convert only from `noexcept` to potentially-throwing.

## Concept Map Outline

- **Parameters and default arguments:** The function type comes from adjusted parameters; default arguments live on declarations, outside the type.
  - **Parameter adjustment:** Parameter types are rewritten before the function type is formed.
    - **Arrays become pointers:** const int a[10] is const int*; only the outermost bound is lost.
    - **Functions become pointers:** A parameter int cb(int) means int (*cb)(int).
    - **Top-level cv dropped:** void f(const int) and void f(int) declare the same function.
    - **Array references kept:** int (&a)[N] keeps the bound, so templates can deduce N.
  - **Default arguments:** Caller-side expressions attached to a declaration.
    - **Bound at declaration:** Names are looked up where the declaration appears.
    - **Evaluated per call:** The expression runs again at every call that uses it.
    - **Forbidden names:** No this, no locals, and no other parameter in a potentially-evaluated use.
    - **Accumulation:** Later declarations in the same scope may add defaults right to left, never repeat one.
    - **Other scopes:** A block-scope redeclaration gets a completely separate set of defaults.
  - **Defaults and dispatch:** Defaults come from what the caller sees, not what runs.
    - **Virtual functions:** The default comes from the static type, the body from the final overrider.
    - **Function pointers:** A pointer's type has no defaults, so every argument must be passed.
  - **Variadic functions:** Arguments matching ... get fixed conversions instead of parameter types.
    - **Default promotions:** bool, char and short become int; float becomes double; nullptr_t becomes void*.
    - **va_arg type:** Must name the promoted type; va_arg(ap, float) is undefined behaviour.
    - **Non-trivial classes:** Passing them or scoped enums through ... is conditionally-supported.
    - **Missing comma:** C++26 deprecates void f(int...) without a comma before the ellipsis.
  - **Most vexing parse:** Anything that can be a declaration is a declaration.
    - **Widget w(Timer()):** Declares a function taking a pointer to function returning Timer.
    - **Fixes:** Use braces, extra parentheses around the argument, or = initialization.
  - **Function type:** Return type, parameter-type-list, noexcept, and member qualifiers.
    - **noexcept since C++17:** Pointers convert from noexcept to potentially-throwing, never back.
    - **Overloaded addresses:** The target type picks the overload when taking an overloaded function's address.
    - **Standard library:** Since C++20, forming pointers to most std functions is unspecified or ill-formed.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.fct.default], [class.virtual])

What does this program print?

```cpp
#include <cstdio>

struct Base {
  virtual void hi(int n = 1) const { std::printf("Base %d\n", n); }
  virtual ~Base() = default;
};
struct Der : Base {
  void hi(int n = 2) const override { std::printf("Der %d\n", n); }
};

int main() {
  Der d;
  const Base& b = d;
  b.hi();
  d.hi();
}
```

A. `Der 2`, then `Der 2`
B. `Base 1`, then `Der 2`
C. `Der 1`, then `Der 2`
D. Ill-formed: an override cannot change a default argument

**Answer (C):** `Der 1`, then `Der 2`

**Why:** The call through `b` is virtual, so `Der::hi` runs, but default arguments are supplied by the caller from the declaration found through the static type, which is `Base::hi` with default 1. The call through `d` sees `Der::hi` and its default 2. Changing a default in an override is legal, merely confusing.

### Question 2 [warmup] ([dcl.ambig.res], [dcl.fct])

Is this program well-formed?

```cpp
struct Timer {};
struct Widget {
  Widget(Timer) {}
  int size() const { return 1; }
};

int main() {
  Widget w(Timer());
  return w.size();
}
```

A. Well-formed: `w` is a `Widget` built from a value-initialized `Timer`, and `main` returns 1
B. Well-formed, but the `Timer` temporary dangles
C. Ill-formed: `Timer()` cannot be used as a constructor argument
D. Ill-formed: `w` declares a function, so `w.size()` is invalid

**Answer (D):** Ill-formed: `w` declares a function, so `w.size()` is invalid

**Why:** [dcl.ambig.res] resolves anything that can be a declaration as a declaration. `Timer()` can be read as a parameter of type "function returning `Timer`", adjusted to a pointer to function, so `w` is a function declaration. Member access on a function is ill-formed. Writing `Widget w{Timer{}};` or `Widget w((Timer()));` gives the object the first option describes.

### Question 3 [warmup] ([dcl.fct])

What is `decltype(f)`?

```cpp
void f(const int a[10]);
```

A. `void(const int[10])`
B. `void(const int*)`
C. `void(int*)`
D. `void(const int* const)`

**Answer (B):** `void(const int*)`

**Why:** A parameter of type "array of `const int`" is adjusted to "pointer to `const int`", and the bound 10 is discarded. The `const` applies to the elements, so it survives; only top-level cv-qualifiers on the parameter itself are removed, and there are none here. A reference-to-array parameter would have kept the bound.

### Question 4 [tricky] ([dcl.fct.default])

What does this program print?

```cpp
#include <cstdio>

int x = 1;
void show(int a = x) { std::printf("%d\n", a); }

int main() {
  int x = 2;
  (void)x;
  ::x = 3;
  show();
}
```

A. `1`: the default is evaluated when `show` is declared
B. `2`: the default is evaluated in the caller's scope
C. `3`
D. Ill-formed: a default argument cannot name a variable

**Answer (C):** `3`

**Why:** The name `x` in the default argument is looked up where `show` is declared, so it means `::x`, not the local `x` in `main`. But the expression is evaluated at each call that uses it, and by then `::x` is 3. Default arguments may name variables with static storage duration; only locals, `this` and, in evaluated contexts, other parameters are forbidden.

### Question 5 [tricky] ([dcl.fct.default])

Is this program well-formed, and if so what does it print?

```cpp
#include <cstdio>

void f(int, int);
void f(int, int = 2);
void f(int = 1, int);
void f(int a, int b) { std::printf("%d %d\n", a, b); }

int main() { f(); }
```

A. Ill-formed: `void f(int = 1, int)` gives a default to a parameter followed by one without
B. Well-formed; prints `1 2`
C. Ill-formed: default arguments must all appear on the first declaration
D. Ill-formed: the definition must repeat the default arguments

**Answer (B):** Well-formed; prints `1 2`

**Why:** For a non-template function, later declarations in the same scope may add default arguments. By the third declaration the second parameter already has a default from a previous declaration, so giving the first one a default is allowed; the right-to-left rule counts defaults from earlier declarations too. The definition must not repeat a default, and here it does not. The first option would be correct if the second declaration were missing.

### Question 6 [tricky] ([conv.fctptr], [except.spec], [dcl.fct])

In C++23, which line makes this translation unit ill-formed?

```cpp
void f() {}
void g() noexcept {}

void (*p1)() = f;            // #1
void (*p2)() = g;            // #2
void (*p3)() noexcept = f;   // #3
void (*p4)() noexcept = g;   // #4
```

A. #2: a `noexcept` function cannot be stored in a plain function pointer
B. #3
C. #4: `noexcept` cannot appear in a pointer declarator
D. None: `noexcept` is not part of the function type

**Answer (B):** #3

**Why:** Since C++17, `noexcept` is part of the function type. The function pointer conversion goes only from pointer-to-`noexcept`-function to pointer-to-potentially-throwing function, which makes #2 valid. #3 would claim that `f` never throws, so no conversion exists and it is ill-formed. The last option describes C++14.

### Question 7 [standardese] ([expr.call], [conv.fpprom], [cstdarg.syn])

What does the standard say about this program?

```cpp
#include <cstdarg>
#include <cstdio>

double sum(int n, ...) {
  va_list ap;
  va_start(ap, n);
  double s = 0;
  for (int i = 0; i < n; ++i) s += va_arg(ap, double);
  va_end(ap);
  return s;
}

int main() {
  float f = 1.5f;
  std::printf("%g\n", sum(2, f, 2.5));
}
```

A. Undefined behavior: a `float` is passed but read as `double`
B. Implementation-defined: the output depends on the calling convention
C. Ill-formed: a `float` cannot be passed to an ellipsis
D. It prints `4`

**Answer (D):** It prints `4`

**Why:** An argument with no corresponding parameter undergoes the default argument promotions, and `float` is promoted to `double` before the call. So both variadic arguments really are `double`, and `va_arg(ap, double)` reads them correctly, giving 4. Reading with `va_arg(ap, float)` would be the undefined behaviour the first option describes.

### Question 8 [standardese] ([dcl.fct.default])

What does this program print?

```cpp
#include <cstdio>

void f(int n = 7);

void g() {
  void f(int n = 9);
  f();
}

void f(int n) { std::printf("%d\n", n); }

int main() {
  f();
  g();
}
```

A. `7`, then `9`
B. `7`, then `7`
C. `9`, then `9`
D. Ill-formed: the block-scope declaration redefines a default argument

**Answer (A):** `7`, then `9`

**Why:** [dcl.fct.default] says declarations in different scopes have completely distinct sets of default arguments. The block-scope declaration in `g` is in a different scope from the namespace-scope one, so giving it a different default is not a redefinition, and calls inside `g` see 9. Calls in `main` see only the namespace-scope declaration and get 7.
