# Contracts

> C++26 adds preconditions, postconditions and contract_assert. A contract assertion is a redundant check whose evaluation semantic, from ignore to quick-enforce, is chosen by the implementation rather than written in the code.

- **Source:** C++ Atlas (https://cppatlas.com/topics/contracts)
- **Track:** C++26
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [basic.contract.general] (https://eel.is/c++draft/basic.contract.general), [basic.contract.eval] (https://eel.is/c++draft/basic.contract.eval), [basic.contract.handler] (https://eel.is/c++draft/basic.contract.handler), [dcl.contract.func] (https://eel.is/c++draft/dcl.contract.func), [dcl.contract.res] (https://eel.is/c++draft/dcl.contract.res), [stmt.contract.assert] (https://eel.is/c++draft/stmt.contract.assert), [expr.prim.id.unqual] (https://eel.is/c++draft/expr.prim.id.unqual), [expr.call] (https://eel.is/c++draft/expr.call), [support.contract] (https://eel.is/c++draft/support.contract), [structure.specifications] (https://eel.is/c++draft/structure.specifications)
- **cppreference links:** [Contract assertions](https://en.cppreference.com/w/cpp/language/contracts), [Function contract specifiers](https://en.cppreference.com/w/cpp/language/function), [contract_assert statement](https://en.cppreference.com/w/cpp/language/contract_assert), [Standard library header <contracts>](https://en.cppreference.com/w/cpp/header/contracts), [std::contracts::contract_violation](https://en.cppreference.com/w/cpp/contract/contract_violation), [assert](https://en.cppreference.com/w/cpp/error/assert), [C++ attribute: assume](https://en.cppreference.com/w/cpp/language/attributes/assume)

## The one idea

A contract assertion states something that a correct program already guarantees. It is a redundant check, not logic. The code says *what* should be true; how that check behaves, whether it is skipped, logged, or fatal, is decided by the implementation, usually through a build flag, and can even differ from one evaluation to the next.

This is C++26, specified by P2900R14 and adopted into the working draft in February 2025. Everything here follows N5050, the final C++26 draft that went to the international ballot. That ballot closed in October 2026 and was reported as not approved, with contracts at the centre of the dispute, so check the status before you quote it as published ISO C++. Compiler support is experimental: GCC 16 needs `-std=c++26 -fcontracts`, and it differs from the draft in a few places noted below.

> **Mental model.** Write each predicate so that deleting it, checking it, or checking it twice would leave a correct program unchanged. Every rule in this feature follows from protecting that property.

## Three kinds of assertion

A **precondition** is written `pre(expr)` after the declarator. It is checked after the arguments have initialized the parameters and before the function body runs. A **postcondition** is written `post(expr)` or `post(r: expr)`. It is checked when the function returns normally, after local variables are destroyed and before the parameters are. `r` is a **result binding** that names the returned object. An **assertion statement** is written `contract_assert(expr);` and works like any other statement.

```cpp
#include <contracts>

int isqrt(const int x)
  pre(x >= 0)
  post(r: r * r <= x && (r + 1) * (r + 1) > x)
{
  int r = 0;
  while ((r + 1) * (r + 1) <= x) ++r;
  contract_assert(r >= 0);
  return r;
}
```

`contract_assert` is a full keyword. It was not named `assert` so that it would not clash with the `<cassert>` macro. `pre` and `post` are identifiers with special meaning, so `int pre = 0;` is still valid. You can write any number of `pre` and `post` specifiers in any order, and each kind is evaluated in the order it was written. A postcondition is never checked when the function exits by an exception or by `longjmp`.

## Where function contract specifiers go

Specifiers belong to a function's **first declaration**. A later declaration may leave them out or repeat the whole sequence, which must match the original under the ODR. It may not repeat only part of the sequence, and it may not add specifiers that the first declaration lacked. If two translation units each contain a first declaration and the sequences differ, the program is ill-formed, no diagnostic required.

The specifiers are not part of the function's type. Overload resolution ignores them, so two templates that differ only in their contracts are ambiguous. A pointer to function, a pointer to member function, or a function type alias cannot carry specifiers. A call through a pointer still checks the target's assertions, because they belong to the function rather than to the expression used to call it.

In C++26 these declarations may not have specifiers:

- a virtual function;
- a deleted function;
- a function defaulted on its first declaration. `T::T() = default;` written after `T();` in the class is not a first declaration, but it may not add specifiers either.

Contracts on virtual functions were adopted into the C++29 working draft (P3097R3) in June 2026. Under that design, a virtual call checks the statically chosen function's preconditions and then the final overrider's. None of that is in C++26.

Lambdas, constructors, destructors, `main`, and coroutines may all have contracts. A lambda's specifiers go in the lambda declarator and apply to its call operator. A name used only inside a contract assertion cannot trigger an implicit capture, so `[=] pre(i > 0) {}` is ill-formed unless `i` is captured explicitly or used elsewhere in the body. That rule keeps adding a check from changing a closure's layout. In a coroutine, a predicate may not contain `co_await` or `co_yield`, and a postcondition may not odr-use a non-reference parameter, because the coroutine works on mutable copies of its parameters.

## Predicates see a const world

Inside a predicate, an id-expression that names a variable declared outside the assertion has `const` type. This covers parameters, locals, globals, and anything reached through a reference. `this` becomes a pointer to const, and the result binding is a const lvalue. Rather than banning side effects, the language makes the common accidental mutations fail to compile.

```cpp
struct Buffer {
  int n = 0;
  int size() { return n; }               // forgot const
  int csize() const { return n; }
};

void use(Buffer& b) pre(b.csize() > 0);  // OK
// void bad(Buffer& b) pre(b.size() > 0);  // error: b is a const lvalue here
// void inc(int x) pre(++x > 0);           // error: x is const in the predicate
```

The const applies to the name, not to the object. A `mutable` member, a `const_cast`, or a function that modifies a global can still produce a side effect. That is legal, but it is a trap, as the next section shows.

> **Pitfall.** A postcondition that reads a by-value parameter needs that parameter to be declared `const` on every declaration, including declarations that do not mention the postcondition. Without that rule, the body could modify the parameter and the postcondition would check the wrong value. Arrays decay, so `const int a[10]` is `const int*`, not `const int* const`, and still does not qualify.

## Four evaluation semantics

Each evaluation of a contract assertion uses one of four semantics:

- **ignore**: the predicate is not evaluated. It is still odr-used, so it must compile, and templates in it are instantiated.
- **observe**: the predicate is checked. On a violation, the contract-violation handler runs, and if it returns, execution continues after the assertion.
- **enforce**: the predicate is checked. On a violation, the handler runs, and if it returns, the program is *contract-terminated*.
- **quick-enforce**: the predicate is checked. On a violation, the program is contract-terminated immediately, without calling the handler.

Observe, enforce, and quick-enforce are the checking semantics, and enforce and quick-enforce are the terminating ones. Contract termination means calling `std::terminate`, calling `std::abort`, or simply stopping execution, and the choice is implementation-defined. Which semantic applies is implementation-defined *for each evaluation*. The standard recommends that implementations offer an all-ignore mode and an all-enforce mode, with enforce as the default. GCC selects the semantic with `-fcontract-evaluation-semantic=ignore|observe|enforce|quick_enforce`, defaulting to enforce.

A violation happens when the predicate is false, when its evaluation exits via an exception, or, during constant evaluation, when it is not a core constant expression.

> **Standardese.** Under a checking semantic, "it is unspecified whether the predicate is evaluated" ([basic.contract.eval]). The implementation may determine the value another way, with no side effects. Consecutive assertions are "evaluated in sequence", and each may be repeated an implementation-defined number of times, as long as the first occurrences keep their order. So a side effect in a predicate may happen zero, one, or several times, even with enforce.

Checking does not make undefined behaviour inside the predicate safe. If the predicate overflows a signed integer, the compiler may assume that never happens and fold the check away. To stop undefined behaviour *after* a check from reaching back in time and removing the check, the standard places an **observable checkpoint** before each checking evaluation, and another after the handler returns.

## The contract-violation handler

On a violation under observe or enforce, the implementation calls `::handle_contract_violation(const std::contracts::contract_violation&)`. Whether you can replace it is implementation-defined, and `__cpp_lib_replaceable_contract_violation_handler` reports the answer. `<contracts>` is freestanding. The `contract_violation` object cannot be copied, and you cannot create one yourself. It provides these observers:

- `kind()`, which returns `assertion_kind::pre`, `post`, or `assert`;
- `semantic()`, which returns the `evaluation_semantic` used;
- `is_terminating()`;
- `detection_mode()`, which returns `predicate_false` or `evaluation_exception`;
- `comment()`, usually the text of the predicate;
- `location()`, the source location.

`invoke_default_contract_violation_handler(v)` hands the violation to the default handler.

```cpp
#include <contracts>
#include <cstdio>
#include <exception>

void handle_contract_violation(const std::contracts::contract_violation& v) {
  std::fprintf(stderr, "%s:%u: %s\n", v.location().file_name(),
               (unsigned)v.location().line(), v.comment());
  if (v.detection_mode() == std::contracts::detection_mode::evaluation_exception)
    std::fprintf(stderr, "  (the predicate threw)\n");
  std::contracts::invoke_default_contract_violation_handler(v);
}
```

When the predicate throws, the handler runs inside an active implicit handler for that exception, so `std::current_exception()` or `throw;` can reach it. P2900R14 also had an `evaluation_exception()` observer returning `exception_ptr`, but it is not in N5050.

The handler may throw an exception instead of returning. For a precondition or postcondition, the effect is as if the function body exited with that exception. A function-try-block cannot catch it, and in a `noexcept` function the result is `std::terminate`. For `contract_assert`, the exception propagates from the statement like any other throw.

> **Pitfall.** GCC 16 spells the observer `mode()` instead of `detection_mode()`. It reports `predicate_false` even when the predicate threw, although it does call the handler from inside the exception's handler. It also accepts some forms the draft forbids: specifiers on deleted functions, on functions defaulted on their first declaration, and on function pointer declarations, and coroutine postconditions that read parameters. Trust the draft.

## Constant evaluation

Contract assertions are evaluated during constant evaluation too, with a semantic the implementation chooses. A violation there makes the program ill-formed under a terminating semantic. Under observe it produces a diagnostic, and evaluation continues. There is no handler at compile time.

```cpp
constexpr int half(int x) pre(x % 2 == 0) { return x / 2; }

static_assert(half(4) == 2);
// constexpr int a = half(3);
// enforce: error; observe: warning, a == 1; ignore: accepted silently
```

To decide whether a variable is constant-initialized, the implementation pretends that every assertion uses ignore. A failing check therefore cannot quietly turn static initialization into dynamic initialization. If one inline function sees different semantics in different translation units, and a predicate's side effect changes a constant's value, the result is an ODR violation.

## Relation to assert, [[assume]] and the library

`assert` is a macro controlled by `NDEBUG`. It cannot appear on a declaration, and it has no handler. `contract_assert` is a language construct that `NDEBUG` does not affect. An unchecked contract assertion never licenses the optimizer to assume that its predicate holds. That job belongs to `[[assume(expr)]]`, which is the opposite tool: a false assumption is undefined behaviour, while a false contract is a reportable violation. An "assume" semantic was deliberately left out of C++26.

The C++20 contracts design, P0542, was removed in 2019 before it shipped. It used attributes such as `[[expects: x > 0]]`, `[[ensures r: r > 0]]`, and `[[assert: p]]`, with `default`, `audit`, and `axiom` levels, a global build level, and a continuation mode. Violating an unchecked contract was undefined behaviour, which let compilers assume it held. P2900 replaces all of that with plain syntax, no levels, and semantics chosen per evaluation.

C++26 also adds a **hardened implementation**, specified by P3471. In a hardened implementation, a *Hardened preconditions:* clause in the library is checked with a contract assertion that uses a terminating semantic. Examples are `vector::operator[]`, `span::front`, and `optional::operator*`. In a non-hardened implementation, violating one is still undefined behaviour. Whether an implementation is hardened is implementation-defined. GCC 16 defines none of the `__cpp_lib_hardened_*` macros, and its `_GLIBCXX_ASSERTIONS` checks do not go through the contracts machinery.

## What to remember

- `pre`, `post(r: ...)`, and `contract_assert` express redundant checks. A correct program behaves the same whether they are checked or not.
- Specifiers live on the first declaration, are not part of the function type, and in C++26 are banned on virtual, deleted, and first-declaration-defaulted functions.
- Inside a predicate, outside variables, `*this`, and the result binding are const. A postcondition that reads a by-value parameter needs that parameter `const` on every declaration.
- The semantic (ignore, observe, enforce, or quick-enforce) is implementation-defined for each evaluation. Enforce is the recommended default.
- A predicate may be evaluated zero, one, or several times, so keep side effects out of it.
- A throwing predicate is a violation. A throwing handler acts as if the function body threw, so a `noexcept` function terminates.
- During constant evaluation, a violation is an error under a terminating semantic and a diagnostic under observe.
- Contracts never feed the optimizer; `[[assume]]` does. Library hardening reuses the machinery with a terminating semantic.
- GCC 16 support is experimental and deviates in a few places: it names the observer `mode()` and accepts some ill-formed declarations.

## Concept Map Outline

- **Contracts (C++26):** Redundant checks via pre, post and contract_assert; how they are checked is chosen by the implementation.
  - **Three assertion kinds:** Preconditions, postconditions and assertion statements, each with a bool predicate.
    - **pre(expr):** Checked after parameters are initialized, before the body runs, in lexical order.
    - **post(r: expr):** Checked on normal return only; r is a const lvalue naming the result object.
    - **contract_assert(expr);:** A full keyword and a statement; unaffected by NDEBUG, unlike the assert macro.
  - **Placement rules:** Specifiers attach to the function's first declaration and are not part of its type.
    - **First declaration:** Later declarations omit them or repeat the same sequence; adding or partly repeating is an error.
    - **Not in the type:** Ignored by overload resolution; pointers to functions and type aliases cannot carry them.
    - **Banned in C++26:** Virtual functions, deleted functions, and functions defaulted on first declaration. Virtual support is C++29 (P3097).
    - **Lambdas and coroutines:** Allowed. Contract-only uses cannot trigger implicit capture; coroutine posts cannot read by-value parameters.
  - **Const predicates:** Outside variables, *this and the result binding are const inside a predicate.
    - **Implicit const:** Calling a non-const member or incrementing a parameter in a predicate is ill-formed.
    - **Const parameters for post:** A by-value parameter read in a postcondition must be const on every declaration.
    - **Side effects:** Still possible via mutable or const_cast; a predicate may run zero, one or several times.
  - **Evaluation semantics:** Implementation-defined per evaluation; enforce is the recommended default.
    - **ignore:** Predicate not evaluated, but still odr-used, so it must compile.
    - **observe:** Checked; on violation the handler runs and execution continues if it returns.
    - **enforce:** Checked; handler runs, then the program is contract-terminated if it returns.
    - **quick-enforce:** Checked; contract-terminated at once without calling the handler.
    - **Constant evaluation:** A violation is ill-formed under a terminating semantic and a diagnostic under observe.
  - **Violation handling:** ::handle_contract_violation receives a const std::contracts::contract_violation&.
    - **Replaceable handler:** Replaceability is implementation-defined; __cpp_lib_replaceable_contract_violation_handler reports it.
    - **Observers:** kind, semantic, is_terminating, detection_mode, comment, location. GCC 16 spells detection_mode as mode.
    - **Throwing predicate:** A violation; the handler runs inside an active handler for that exception.
    - **Throwing handler:** Acts as if the function body threw; in a noexcept function, std::terminate is called.
  - **Related features:** How contracts differ from older and neighbouring mechanisms.
    - **[[assume]]:** A false assumption is UB; contracts never let the optimizer assume an unchecked predicate.
    - **C++20 attributes:** [[expects]], [[ensures]] and [[assert]] with levels were removed in 2019 before shipping.
    - **Library hardening:** In a hardened implementation, library Hardened preconditions are checked with a terminating semantic.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.contract.func], [dcl.contract.res])

Under the C++26 draft, is this declaration well-formed?

```cpp
int isqrt(int x)
  pre(x >= 0)
  post(r: r * r <= x && (r + 1) * (r + 1) > x);
```

A. Well-formed
B. Ill-formed: a postcondition cannot refer to function parameters
C. Ill-formed: the postcondition odr-uses `x`, so `x` must be declared `const` on every declaration
D. Well-formed, but undefined behavior if the body modifies `x`

**Answer (C):** Ill-formed: the postcondition odr-uses `x`, so `x` must be declared `const` on every declaration

**Why:** Postconditions may name parameters, but if a postcondition odr-uses a non-reference parameter, that parameter must have `const` type on every declaration of the function, including declarations without the postcondition. Otherwise the body could change `x` and the check would test a different value from the one the caller passed. Writing `const int x` fixes it. The "undefined behavior" answer is tempting because it describes what would go wrong without the rule, but the language makes the declaration ill-formed instead of leaving it to run-time behavior.

### Question 2 [warmup] ([dcl.contract.func], [expr.call])

With the enforce semantic for every contract assertion, what does this program print?

```cpp
#include <cstdio>
#include <stdexcept>

int parse(const int x) post(r: r > 0) {
  if (x < 0) throw std::invalid_argument("negative");
  return x;
}

int main() {
  try {
    parse(-1);
  } catch (const std::invalid_argument&) {
    std::puts("invalid_argument");
  }
}
```

A. `invalid_argument`
B. A contract-violation diagnostic, then the program is contract-terminated
C. A contract-violation diagnostic, then `invalid_argument`
D. Nothing; `std::terminate` is called because an exception passes through a postcondition

**Answer (A):** `invalid_argument`

**Why:** A postcondition assertion is associated only with exiting the function normally. When `parse` exits via an exception, its postconditions are not evaluated at all, so there is no violation and the exception reaches the handler in `main`. The answers with a diagnostic assume the postcondition is checked on every exit, which is wrong. A postcondition that a function does or does not throw is one of the features P2900 deliberately leaves out.

### Question 3 [warmup] ([expr.call], [basic.contract.eval], [dcl.contract.func])

Assume a checking semantic, and assume each predicate is evaluated exactly once. What does this program print?

```cpp
#include <cstdio>

bool say(const char* s) { std::puts(s); return true; }

int f()
  pre(say("pre a"))
  post(r: say("post b"))
  pre(say("pre c"))
{
  std::puts("body");
  return 0;
}

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

A. `pre a`, `post b`, `pre c`, `body`
B. Nothing: the program is ill-formed because `pre` must come before `post`
C. `pre c`, `pre a`, `body`, `post b`
D. `pre a`, `pre c`, `body`, `post b`

**Answer (D):** `pre a`, `pre c`, `body`, `post b`

**Why:** `pre` and `post` specifiers may appear in any order, so the declaration is fine. The preconditions are evaluated in sequence, in lexical order, after the parameters are initialized and before the body runs. The postconditions are evaluated in sequence after the body returns normally. The `pre a`, `post b`, `pre c` answer reads the specifiers as a single list evaluated left to right. The assumption in the question matters: under a checking semantic it is unspecified whether a predicate is actually evaluated, and an implementation may repeat assertions, so side effects like these `puts` calls are not guaranteed in general.

### Question 4 [tricky] ([expr.prim.id.unqual], [basic.contract.general], [dcl.contract.func])

Which of these declarations is ill-formed under the C++26 draft?

```cpp
struct Buffer {
  int n = 0;
  int size() { return n; }
  int csize() const { return n; }
};

void a(Buffer& b) pre(b.csize() > 0);
void b(Buffer& b) pre(b.size() > 0);
void c(Buffer* p) pre(p != nullptr);
void d(const Buffer& b) post(b.n >= 0);
```

A. `a`
B. `b`
C. `c`
D. `d`

**Answer (B):** `b`

**Why:** Inside a contract predicate, an id-expression that names a variable declared outside the assertion has `const` type, and that includes reference parameters. So `b` is a `const Buffer` lvalue in the predicate, and calling the non-const `size()` on it is ill-formed. In `c`, only the pointer `p` becomes const, which does not stop a comparison. In `d`, the parameter is a reference, so the postcondition does not require it to be declared `const`. The const requirement for postconditions applies only to non-reference parameters.

### Question 5 [tricky] ([basic.contract.eval], [except.terminate], [basic.contract.handler])

Assume the implementation lets you replace the contract-violation handler, and the enforce semantic is used. What happens?

```cpp
#include <contracts>
#include <cstdio>
#include <stdexcept>

void handle_contract_violation(const std::contracts::contract_violation& v) {
  throw std::logic_error(v.comment());
}

void g(int x) noexcept pre(x > 0) {}

int main() {
  try {
    g(0);
  } catch (const std::logic_error&) {
    std::puts("caught");
  }
}
```

A. `std::terminate` is called
B. `caught` is printed: the precondition is checked by the caller, outside the `noexcept` boundary
C. The handler returns via the exception, so the program is contract-terminated without unwinding
D. Undefined behavior

**Answer (A):** `std::terminate` is called

**Why:** If a handler invoked from a function contract assertion exits via an exception, the behavior is as if the function body had exited via that exception. `g` is `noexcept`, so the search for a handler leaves a non-throwing function and `std::terminate` is called. This happens even though implementations may emit precondition checks at the call site, which is why `caught` is tempting. A handler that throws from a plain `contract_assert` instead propagates the exception from that statement.

### Question 6 [tricky] ([expr.prim.lambda.closure], [dcl.contract.func])

Under the C++26 draft, which lambda makes the program ill-formed?

```cpp
void test() {
  int i = 1;
  auto f1 = [i] pre(i > 0) {};
  auto f2 = [=] pre(i > 0) {};
  auto f3 = [=] { contract_assert(i > 0); (void)i; };
  auto f4 = [&] { return i; };
}
```

A. `f1`: explicit captures cannot be used in a precondition
B. `f2`
C. `f3`: `contract_assert` cannot appear in a lambda body
D. None of them

**Answer (B):** `f2`

**Why:** If every potential reference to an implicitly captured local entity appears inside contract assertions, the program is ill-formed. Adding a check must never cause a new capture, because a capture would change the closure's layout. `f2` uses `i` only in its precondition, so it breaks the rule. `f1` captures `i` explicitly, and `f3` also uses `i` outside the assertion, so both are fine. GCC 16 rejects `f2` with "not implicitly captured by a contract assertion".

### Question 7 [standardese] ([basic.contract.eval], [expr.const], [intro.compliance.general])

Under the C++26 draft, what is true of the declaration of `a`?

```cpp
constexpr int half(int x) pre(x % 2 == 0) { return x / 2; }

constexpr int a = half(3);
```

A. It is always ill-formed, because a precondition is false in a constant expression
B. `a` falls back to dynamic initialization, and the handler runs at program startup
C. It is ill-formed if the evaluation uses enforce or quick-enforce. With observe, a diagnostic is issued and `a` is 1. With ignore, it is accepted silently
D. It is always accepted, because contract assertions are not evaluated during constant evaluation

**Answer (C):** It is ill-formed if the evaluation uses enforce or quick-enforce. With observe, a diagnostic is issued and `a` is 1. With ignore, it is accepted silently

**Why:** Contract assertions are evaluated during constant evaluation, with an implementation-chosen semantic. A violation in a manifestly constant-evaluated context makes the program ill-formed under a terminating semantic. Under observe, the implementation must issue a diagnostic but keeps going. The dynamic-initialization answer is wrong because constant-initializability is decided as if every assertion used ignore, so `a` is still constant-initialized, and there is no handler at compile time. GCC 16 shows exactly this pattern: an error under enforce and quick_enforce, a warning under observe, and silence under ignore.

### Question 8 [standardese] ([dcl.contract.func], [dcl.fct.def.coroutine], [expr.await])

In C++26, as specified in the final draft N5050, which of these may *not* have a function contract specifier?

A. A constructor, as in `S(int n) pre(n > 0);`
B. A coroutine whose precondition reads a by-value parameter
C. The function `main`
D. A virtual member function, as in `virtual void f(int i) pre(i > 0);`
E. A redeclaration that repeats exactly the same specifiers as the first declaration

**Answer (D):** A virtual member function, as in `virtual void f(int i) pre(i > 0);`

**Why:** In C++26, [dcl.contract.func] says a virtual function, a deleted function, or a function defaulted on its first declaration shall not have a function-contract-specifier-seq. Contracts for virtual functions (P3097R3) were adopted only into the C++29 working draft, in June 2026. Constructors, coroutines, and `main` may have contracts. Coroutines are restricted only in that a postcondition may not odr-use a non-reference parameter, and a predicate may not contain `co_await`. A non-first declaration may either omit the specifiers or repeat the same sequence.
