July 16, 2026

C++26 Contracts: Preconditions, Postconditions, and contract_assert in Practice

C++26 contracts make runtime expectations visible in the code, but they do not replace validation, error handling or careful API design.

A function can be perfectly valid from the type system’s perspective and still be called incorrectly:

divide(total, 0);
buffer.subspan(buffer.size() + 1);
stateMachine.activate(); // while shutdown is already in progress

None of these calls necessarily contains a type error. The problem is that the caller violated a rule that exists outside the function signature.

Before C++26, we usually expressed such rules with documentation, assert, exceptions, error codes, stronger types, or project-specific macros. All of these tools remain useful, but they communicate different kinds of failure.

C++26 introduces language-level contract assertions with three forms: pre, post, and contract_assert. The syntax is simple. The difficult part is deciding which conditions are genuine contracts and which conditions are normal runtime errors.

Note

This article focuses on the practical programming model. Contracts are new, compiler support is still limited, and implementation options differ. Treat the examples as C++26-oriented code and check your toolchain before using them in production.

c++26 contracts

The real problem: types do not express every valid state


C++ types can express many useful rules. An enum can restrict a mode. A strong type can stop us from mixing milliseconds with bytes. A reference can communicate that an object must exist.

But many API rules depend on runtime values and object state:

  • An index must be smaller than a buffer size.
  • A denominator must not be zero.
  • A connection must be established before sending data.
  • A range must satisfy begin <= end.
  • A returned object must be initialized and internally consistent.

These rules are often written in comments:

// index must be smaller than data.size()
std::byte readByte(std::span<const std::byte> data,
                   std::size_t index);

The comment may be correct, but the compiler does not understand it. It can become outdated, and the caller may never see it during code review.

A contract assertion moves the runtime rule into the language-level interface:

std::byte readByte(std::span<const std::byte> data,
                   std::size_t index)
    pre(index < data.size());

The rule is now attached to the function instead of living only in documentation.

The three forms of C++26 contract assertions


C++26 provides three places to express an expected program state:

  • pre(condition) — a condition associated with entering a function.
  • post(condition) — a condition associated with leaving a function normally.
  • contract_assert(condition) — a condition checked at a specific point inside a function or lambda body.
int clampValue(const int value,
               const int low,
               const int high)
    pre(low <= high)
    post(result: result >= low)
    post(result: result <= high)
{
    const int result = std::clamp(value, low, high);

    contract_assert(
        result == value ||
        result == low ||
        result == high);

    return result;
}

The three forms describe different responsibilities:

  • The caller must provide a valid range.
  • The function guarantees that the returned value is inside that range.
  • The implementation expects its internal calculation to produce one of three valid outcomes.

Rule of thumb

If the caller promises it, use pre. If the function promises it, use post. If the implementation expects it internally, use contract_assert.

who owns each promise

Preconditions describe caller responsibility


A precondition says that the caller must establish a valid state before invoking the function.

int divide(int numerator, int denominator)
    pre(denominator != 0)
{
    return numerator / denominator;
}

Calling divide(10, 0) is not a normal alternative result of this API. It means the caller violated the function’s contract.

Several preconditions can be attached to one function:

std::string_view readField(
    std::string_view message,
    std::size_t offset,
    std::size_t length)
    pre(offset <= message.size())
    pre(length <= message.size() - offset)
{
    return message.substr(offset, length);
}

This is better than one large predicate when the conditions describe separate obligations. Diagnostics can identify which expectation failed, and code review can discuss each rule independently.

Warning

Do not use a precondition for data that can legitimately be invalid. User input, network packets, configuration files and device responses still need normal validation and error handling.

Postconditions describe the function’s guarantee


A postcondition describes a property that should hold after the function returns normally.

std::size_t nextIndex(const std::size_t index)
    pre(index < 1024)
    post(result: result == index + 1)
{
    return index + 1;
}

The identifier before the colon is the result binding. It names the object or reference returned by the function.

The name is chosen by the programmer:

Connection createConnection()
    post(connection: connection.isValid());

A postcondition is associated only with a normal return. It is not evaluated when the function exits by throwing an exception.

Postconditions are useful for guarantees such as:

  • The returned value is inside a valid range.
  • The returned handle is initialized.
  • A collection remains sorted.
  • An object has moved into a required state.

They are especially useful when the guarantee is important to callers but easy to lose inside a large implementation.

contract_assert describes an internal invariant


contract_assert is a statement inside a function or lambda body. It expresses an expectation at a specific point in the implementation.

void processMessage(const Message& message)
{
    const Header header = decodeHeader(message);

    contract_assert(header.payloadSize <= message.size());

    dispatchPayload(message, header);
}

This is similar in purpose to a traditional assert, but it participates in the C++26 contracts model and its evaluation semantics.

Typical uses include:

  • Checking an invariant after an internal transformation.
  • Verifying an impossible state in a state machine.
  • Checking relationships between private members.
  • Confirming assumptions after parsing already validated internal data.
void DeviceSession::transitionTo(State next)
{
    contract_assert(isAllowedTransition(state_, next));

    state_ = next;

    contract_assert(state_ == next);
}

The first assertion checks the transition rule. The second checks the result of the update. Neither condition is an expected operational failure.

A practical embedded C++ example


Consider an internal packet queue used by a device daemon. The queue has a fixed capacity and returns the packet removed from the front.

class PacketQueue
{
public:
    explicit PacketQueue(const std::size_t capacity)
        pre(capacity > 0)
        post(capacity_ == capacity)
        : storage_(capacity)
        , capacity_(capacity)
    {
    }

    void push(Packet packet)
        pre(size_ < capacity_)
        post(size_ <= capacity_)
    {
        storage_[writeIndex_] = std::move(packet);
        writeIndex_ = (writeIndex_ + 1) % capacity_;
        ++size_;

        contract_assert(writeIndex_ < capacity_);
    }

    Packet pop()
        pre(size_ > 0)
        post(packet: packet.isValid())
    {
        Packet packet = std::move(storage_[readIndex_]);

        readIndex_ = (readIndex_ + 1) % capacity_;
        --size_;

        contract_assert(readIndex_ < capacity_);
        contract_assert(size_ <= capacity_);

        return packet;
    }

private:
    std::vector<Packet> storage_;
    std::size_t capacity_{};
    std::size_t size_{};
    std::size_t readIndex_{};
    std::size_t writeIndex_{};
};

The contracts make several responsibilities visible:

  • The constructor requires a non-zero capacity.
  • The caller must not push into a full queue.
  • The caller must not pop from an empty queue.
  • The implementation guarantees valid indexes and bounded size.
  • The returned packet must satisfy the queue’s validity rule.

This example also reveals an important design question. If a full queue is a normal runtime condition, then push should not use a precondition. It may need to return bool, std::expected, or another result instead.

Practical design point

The same condition can be a contract in one API and a normal result in another. The deciding factor is whether it can occur during correct use of that API.

Contracts are not input validation


This is the most important distinction when adding contracts to a real system.

Important

A contract violation represents a programming error. It should not represent an expected failure caused by users, networks, filesystems, hardware or remote services.

This is a normal error-handling API:

std::expected<Configuration, ParseError>
parseConfiguration(std::string_view input);

Invalid configuration text is possible even when the program is correct. The caller may have read it from a file, received it over the network, or obtained it from a user.

This would usually be the wrong contract:

Configuration parseConfiguration(std::string_view input)
    pre(isValidConfiguration(input));

The precondition moves a recoverable failure into the “programmer made a mistake” category. It also assumes the predicate will be checked, which is not guaranteed.

A precondition may make sense at a trusted internal boundary:

Configuration buildConfiguration(ValidatedConfigData data)
    pre(data.isInternallyConsistent());

Here the type and architecture already say that validation happened earlier. A violation means an internal layer broke its own rule.

contract violation or normal error

What happens when a contract is violated?


C++26 defines four evaluation semantics. The implementation decides which semantic is used for a contract assertion.

SemanticChecks the condition?What happens after a violation?
ignoreNoThe contract assertion has no effect.
observeYesThe violation handler is invoked. Execution continues if the handler returns normally.
enforceYesThe violation handler is invoked. The program is contract-terminated if the handler returns normally.
quick-enforceYesThe program is contract-terminated without invoking the handler.

This is not standardized as a simple “enabled in Debug, disabled in Release” switch.

The C++ standard does not connect contracts to NDEBUG, optimization levels, CMake build types, or one universal command-line option. The available controls are implementation-specific.

The standard recommends that implementations provide configurations for ignoring all contracts and enforcing all contracts, with enforce as the recommended default. It does not require every implementation to expose all four semantics.

four contract evaluation semantics

A contract predicate cannot implement required behavior


A contract predicate may not be evaluated at all. Even with a checking semantic, the implementation may determine the result without preserving the predicate’s side effects.

Contract assertions may also be evaluated repeatedly. By default, implementations are recommended not to repeat them, but the language model allows repetition.

Therefore, required program behavior must never live inside a contract predicate.

void start(Request& request)
    pre(validateAndInitialize(request)); // wrong

If the contract is ignored, the initialization disappears.

contract_assert(++processedCount < limit); // wrong

The increment may not happen, or the assertion may be evaluated repeatedly.

Prefer predicates that only observe state:

contract_assert(index < buffer.size());
contract_assert(connection_ != nullptr);
contract_assert(state_ == State::ready);
contract_assert(std::ranges::is_sorted(values));

The final example is side-effect-free, but it may be expensive. Contract cost still matters because some production configurations may evaluate the predicate.

Warning

A contract predicate is an observation, not an action. Keep it side-effect-free, deterministic, safe to evaluate, and reasonably cheap.

a contract predicate is an observation

Contracts do not replace assert, concepts or error handling


Contracts add a new tool. They do not make the existing tools obsolete.

MechanismMain purposeTypical question
static_assertCompile-time validationIs this property known and valid during compilation?
Concept / requiresConstrain templates and overloadsIs this function available for this type?
assertTraditional local runtime assertionDoes this internal assumption hold in an assert-enabled build?
preCaller obligationIs this runtime value valid before entering the function?
postFunction guaranteeDid the function establish its promised result?
contract_assertInternal contract assertionDoes this expected state hold at this point?
std::expected / exception / error codeNormal failure handlingHow should the caller handle an operation that may legitimately fail?
[[assume(condition)]]Optimizer assumptionWhat may the optimizer assume is true?

Concepts constrain types. Contracts constrain runtime program states.

template<std::integral T>
T divide(T numerator, T denominator)
    pre(denominator != 0)
{
    return numerator / denominator;
}

std::integral checks whether T is an integer type. The precondition checks whether this particular denominator value is valid.

[[assume]] is also different. It gives the optimizer permission to assume a property. It is not primarily a diagnostic mechanism. Using a false assumption can make program behavior invalid, while a contract assertion describes an expected state and may diagnose its violation.

The contract-violation handler is mainly a diagnostics boundary


For observe and enforce, a violation invokes the program’s global contract-violation handler:

#include <contracts>
#include <cstdio>

void handle_contract_violation(
    const std::contracts::contract_violation& violation)
{
    const auto location = violation.location();

    std::fprintf(
        stderr,
        "Contract violation: %s at %s:%u\n",
        violation.comment(),
        location.file_name(),
        location.line());
}

The std::contracts::contract_violation object provides information such as:

  • The textual representation of the predicate, when provided by the implementation.
  • The assertion kind: precondition, postcondition, or assertion statement.
  • The evaluation semantic.
  • The source location.
  • Whether the violation is terminating.
  • Whether the predicate was false or its evaluation exited through an exception.

There are important limitations. Whether the handler is replaceable is implementation-defined. quick-enforce does not invoke it. The default handler is supplied by the implementation, but no standard header declares the global handler function for you.

The handler can technically throw. For a function contract assertion, that behaves as if the function body exited through the same exception. But using the handler as a general recovery mechanism is risky: the program has already broken one of its expected rules.

Practical use

Use the handler to produce diagnostics, telemetry or a crash report. Do not build ordinary business logic around recovering from contract violations.

Postconditions have some surprising rules


Postconditions look straightforward, but a few details matter in real APIs.

A result binding cannot be used with a void return type:

void reset()
    post(result: result == true); // ill-formed

A void function can still have a postcondition without a result binding:

void reset()
    post(isReady());

If a postcondition uses a non-reference parameter, that parameter must have const type on every declaration:

int nextValue(const int value)
    post(result: result == value + 1)
{
    return value + 1;
}

This version is ill-formed because the by-value parameter used by the postcondition is not const:

int nextValue(int value)
    post(result: result == value + 1);

C++26 also does not provide a built-in old(value) expression. A postcondition can observe the state after the function body, but it cannot directly ask for an automatic snapshot of the value from function entry.

void increment(int& value)
    post(value > 0)
{
    ++value;
}

The postcondition sees the modified value. More complex guarantees such as “the new size equals the old size plus one” may still need a wrapper, helper object, stronger type, or an internal assertion.

C++26 contracts are an MVP, not complete Design by Contract


The C++26 facility deliberately starts with a smaller model. Several features that people may expect from full Design by Contract are not part of the current language facility.

  • There is no dedicated class-invariant syntax.
  • There is no built-in capture of old values for postconditions.
  • There are no standard assertion levels such as cheap, audit or expensive.
  • There is no standard custom message argument in the contract syntax.
  • Virtual functions cannot have function contract specifiers in the current C++26 model.
  • Deleted functions and functions defaulted on their first declaration cannot have function contract specifiers.
  • A function pointer, member-function pointer or function type alias cannot carry contracts directly.

A function’s contracts are still evaluated when the function is invoked indirectly through a pointer. The contract simply does not become part of the pointer type.

Contracts must also remain consistent across declarations. Later declarations may omit them, but if they repeat the contract sequence, it must match the first declaration.

int divide(int numerator, int denominator)
    pre(denominator != 0);

// The definition may omit the repeated contract syntax.
int divide(int numerator, int denominator)
{
    return numerator / denominator;
}

For public APIs, the first declaration in the header is usually the most useful place for preconditions and postconditions. That is where callers discover the contract.

Compiler support is still experimental


At the time of writing in July 2026, GCC 16 includes experimental support for the C++26 contracts proposal. It requires C++26 mode and the contracts option:

g++ -std=c++26 -fcontracts example.cpp

GCC also exposes implementation-specific options for choosing the evaluation semantic:

g++ -std=c++26 -fcontracts \
    -fcontract-evaluation-semantic=enforce \
    example.cpp

The available GCC values include ignored, observed, enforce, and quick_enforce.

Clang’s official C++26 status page still lists P2900R14 contracts as unsupported.

The language feature-test macro is:

__cpp_contracts >= 202502L

The <contracts> library facility can be checked with:

__cpp_lib_contracts >= 202502L

Toolchain note

Do not design a cross-platform production policy around one compiler’s flags. The language defines the semantics, but the configuration mechanism is implementation-specific.

A practical decision table


A useful starting point for API design and code review:

SituationPreferWhy
Caller passes an invalid index to an internal APIpreThe caller broke a programming rule.
Function must return a value inside a rangepostThe implementation promises the result property.
Internal state machine reaches an impossible statecontract_assertThe implementation invariant is broken.
User enters malformed textstd::expected or validation resultInvalid input is a normal runtime possibility.
File is missing or permission is deniedError code, exception or std::expectedThe caller may need to recover differently.
Template requires an integral typeConcept / requiresThe restriction is about types and overload selection.
Property must hold during compilationstatic_assertThe condition is a compile-time rule.
Optimizer may assume a property[[assume]]This is an optimization promise, not a diagnostic check.

The key question is not “can I write this as a contract?” The key question is “what does failure mean to the caller?”

Common mistakes


A few mistakes are likely to appear when teams first adopt contracts.

  • Using contracts for untrusted input. External data still needs real validation.
  • Putting initialization or counters in predicates. The predicate may be skipped or repeated.
  • Assuming Debug means checked and Release means ignored. The standard does not define that build policy.
  • Using expensive predicates everywhere. Some optimized production configurations may still evaluate them.
  • Replacing meaningful errors with preconditions. A timeout, missing file or full queue may be a normal result.
  • Trying to recover from every violation. A violated contract means the program has already entered a state it claimed was invalid.
  • Repeating contracts inconsistently across declarations. The first declaration defines the function’s contract sequence.
  • Adding contracts without reviewing the API boundary. A contract can expose that the function should return an error instead.

A practical review checklist


When reviewing a contract assertion, I would ask these questions:

  1. Can this condition fail during completely correct program execution?
  2. Is the responsibility owned by the caller, the function, or the internal implementation?
  3. Would the caller need a reason and a recovery path instead?
  4. Does the predicate have any side effects?
  5. Is the predicate safe if it is skipped?
  6. Is the predicate safe if it is evaluated more than once?
  7. Is the predicate cheap enough for the intended deployment policy?
  8. Does the contract belong on the public declaration where callers can see it?
  9. Does the project have a documented compiler and evaluation-semantic policy?
  10. Are security and external-input checks still enforced independently of contracts?

If these questions are difficult to answer, the API contract is probably not clear enough yet.

The key idea


If you remember only one thing, remember this:

Tip

A contract describes a rule that correct code is expected never to break. It does not describe every failure that a correct program must be prepared to handle.

pre makes the caller’s responsibility visible. post makes the function’s guarantee visible. contract_assert makes an internal invariant visible.

Used carefully, C++26 contracts can improve API documentation, code review and diagnostics. Used as a replacement for validation or error handling, they can make a system less reliable.

The syntax is the easy part. The real engineering work is deciding whether a failed condition means “the program contains a bug” or “the operation encountered a normal problem”.

Good C++ APIs make that distinction visible.