C++26 adds contracts to the language: preconditions with pre, postconditions with post, and assertions with contract_assert. Unlike the assert macro, they are part of the function declaration, the compiler understands them, and you choose at build time what happens when one fails.
This guide walks through the syntax, the four evaluation semantics, custom violation handlers, and the compiler errors you are likely to hit. Every example was compiled and run with GCC 16.2 through Compiler Explorer, and the outputs below are copied from those runs.
Quick fix: With GCC 16, compile with
g++ -std=c++26 -fcontracts. Choose the behavior with-fcontract-evaluation-semantic=enforce|observe|ignore|quick_enforce. If you seeundefined reference to handle_contract_violation, you forgot-fcontracts. If you seeexpected function body after function declarator, your compiler does not support contracts yet.
Which compilers support C++26 contracts?
| Compiler | Status (November 2026) | Flags |
|---|---|---|
| GCC 16 | Implemented (GCC 16 release notes list P2900R14) | -std=c++26 -fcontracts |
| Clang trunk | Not supported in our test: the syntax is rejected | n/a |
| MSVC | Not checked for this article | n/a |
Check your compiler’s release notes before relying on contracts in shared code. The feature is new, and the examples here describe GCC 16.2 specifically.
What do pre, post, and contract_assert look like?
#include <cstddef>
#include <vector>
#include <iostream>
int get_value(const std::vector<int>& values, std::size_t index)
pre(index < values.size())
{
return values[index];
}
int clamp_percent(const int v)
post(r: r >= 0 && r <= 100)
{
return v < 0 ? 0 : (v > 100 ? 100 : v);
}
int main() {
std::vector<int> v{1, 2, 3};
std::cout << clamp_percent(150) << '\n';
contract_assert(v.size() == 3);
std::cout << get_value(v, 5) << '\n';
}
pre(...)goes after the declarator and is checked when the function is called.post(r: ...)names the return valuerand is checked when the function returns.contract_assert(...)is a statement, not a macro, so it works without any header.
Step 1: How do you build and run a contract check?
- Compile with contracts enabled. The default semantic is
enforce:g++ -std=c++26 -fcontracts -O2 contracts.cpp -o contracts ./contracts100 contract violation in function int get_value(const std::vector<int>&, std::size_t) at /app/example.cpp:6: index < values.size() [assertion_kind: pre, semantic: enforce, mode: predicate_false, terminating: yes] terminate called without an active exceptionYou should see the function signature, file and line, the predicate text, and
terminating: yes. The process ends withSIGABRT, so the shell reports exit status 134. - Note that
clamp_percent(150)printed100and its postcondition passed, andcontract_assertpassed silently.
Note: Contract predicates should not have side effects. GCC treats the objects they reference as
const, which is why some ordinary-looking predicates fail to compile, as shown below.
What are the four evaluation semantics?

| Semantic | Checks predicate? | Calls handler? | Terminates? |
|---|---|---|---|
ignore | No | No | No |
observe | Yes | Yes | No, execution continues |
enforce | Yes | Yes | Yes |
quick_enforce | Yes | No | Yes, immediately |
The same program built with -fcontract-evaluation-semantic=observe reports the violation and keeps going:
contract violation in function int get_value(const std::vector<int>&, std::size_t) at /app/example.cpp:6: index < values.size()
[assertion_kind: pre, semantic: observe, mode: predicate_false, terminating: no]
With quick_enforce, the only output was terminate called without an active exception; the diagnostic line is skipped because no handler runs.
Warning:
observelets the program continue past a broken precondition. In our-O2run, the out-of-bounds read then printed a garbage value; at-O0, the libstdc++ debug assertion inoperator[]caught it instead. Useobserveto roll out new checks in logging mode, not as a safety net.
The GCC 16 online documentation spells some values as ignored and observed, but GCC 16.2 rejects those:
g++: error: unrecognized contract evaluation semantic 'observed'
g++: note: valid arguments to '-fcontract-evaluation-semantic=' are: enforce ignore observe quick_enforce; did you mean 'observe'?
Step 2: How do you install a custom violation handler?
- Define
handle_contract_violationand include<contracts>:#include <contracts> #include <cstdio> void handle_contract_violation(const std::contracts::contract_violation& v) { std::fprintf(stderr, "[contract] %s at %s:%u\n", v.comment(), v.location().file_name(), v.location().line()); } double safe_div(double a, double b) pre(b != 0.0) { return a / b; } int main() { std::printf("%f\n", safe_div(1.0, 0.0)); contract_assert(1 + 1 == 3); std::puts("still running"); } - Build in observe mode and run it:
g++ -std=c++26 -fcontracts -fcontract-evaluation-semantic=observe handler.cpp -o handler ./handler[contract] b != 0.0 at /app/example.cpp:9 inf [contract] 1 + 1 == 3 at /app/example.cpp:13 still runningYou should see your own format instead of the default message.
comment()returns the predicate text, andlocation()returns astd::source_location. - Route the handler to your logging or crash reporting system. In
enforcemode, the program still terminates after your handler returns.
Tip: A custom handler is the practical way to introduce contracts into an existing service: ship with
observe, collect violations in logs, fix callers, then switch toenforce.
What compiler errors will you run into?
| Error | Cause | Fix |
|---|---|---|
undefined reference to `handle_contract_violation(...)' | Built with -std=c++26 but without -fcontracts | Add -fcontracts |
a value parameter used in a postcondition must be const | post reads a non-const by-value parameter | Declare the parameter const |
increment of read-only location | Side effect inside a predicate | Move the side effect out of the contract |
contract predicate is false in constant expression | Violation during constant evaluation | Fix the constant argument |
expected function body after function declarator | Compiler lacks contract support | Use GCC 16 or guard the code |
The const rule for postconditions exists because the function body could modify a by-value parameter before returning, making the check misleading:
int clamp_percent(int v) // error: v must be const
post(r: r >= 0 && r <= v);
int clamp_percent(const int v) // OK
post(r: r >= 0 && r <= v);
Contracts also run during constant evaluation. constexpr int h = half(3); with pre(x % 2 == 0) fails to compile instead of failing at run time.
How do contracts compare with assert?
| Feature | assert | C++26 contracts |
|---|---|---|
| Part of the declaration | No | Yes, pre and post |
| Control | NDEBUG on or off | Four semantics |
| Custom handler | No | Yes |
| Return value checks | Manual | post(r: ...) |
GCC also documents tuning flags such as -fcontract-checks-outlined and -fcontracts-conservative-ipa. Check the GCC manual for their trade-offs before using them in release builds.
How do you keep code portable to compilers without contracts?
The standard feature-test macro is __cpp_contracts, with the value 202502L for C++26. A small wrapper lets the same header build on compilers that reject the syntax:
#if defined(__cpp_contracts)
# define PRE(x) pre(x)
#else
# define PRE(x)
#endif
int inverse_percent(int x) PRE(x != 0) { return 100 / x; }
With GCC 16.2 and -fcontracts, this printed __cpp_contracts=202502. Clang trunk did not define the macro, so the wrapper expanded to nothing and the program built and ran.
Warning: In our test, GCC 16.2 defined
__cpp_contractswith plain-std=c++26too, and the program then failed at link time with the missinghandle_contract_violationreference. The macro guard does not replace the-fcontractsflag on GCC.
For CMake projects, keep both settings next to each other so nobody drops one:
set(CMAKE_CXX_STANDARD 26)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
target_compile_options(app PRIVATE -fcontracts)
endif()
What does the standard leave to the implementation?
Several details you might expect to be fixed are implementation-defined or unspecified, according to cppreference’s summary of the C++26 rules:
- Which semantic is used. The standard defines the four semantics but leaves the choice, and how you select it, to the implementation. The
-fcontract-evaluation-semanticflag is GCC’s mechanism, not a portable one. - How often a predicate runs. A checked predicate may be evaluated more than once, or not at all if the compiler can determine its value. Side effects in predicates are therefore unreliable even when they compile.
- Whether the handler is replaceable. Defining your own
handle_contract_violationworked with GCC 16.2, but the standard lets an implementation refuse it. - How termination happens. A contract-terminated program may call
std::terminate, callstd::abort, or simply stop. GCC’senforcecalledstd::terminatein our runs.
The practical rule is simple: write predicates that are cheap, side-effect free, and safe to evaluate any number of times.
FAQ
Should I replace every assert?
Not yet. Start with function boundaries in new code, where pre and post document the interface. Keep assert where you must also build with compilers that lack contract support.
Can a contract check throw an exception?
If evaluating a predicate throws, that also counts as a contract violation. With enforce or observe, the handler runs while the exception is active, so it can inspect it with std::current_exception().
Are contracts checked in release builds?
That depends on the semantic you choose. Unlike assert, they are not tied to NDEBUG.
Conclusion
With GCC 16, C++26 contracts work today behind -std=c++26 -fcontracts. Write pre and post on interfaces, keep predicates free of side effects, roll out with observe and a custom handler, and move to enforce once violations stop showing up.
Related guides
- CMake Undefined Reference Error: 7 Fixes for C++ Builds
- Fix “GLIBCXX_3.4.xx not found” Errors on Linux
- Speed Up C++ Builds on Linux with ccache and Ninja
- Bazel vs CMake: Which Build System Fits Your Linux C++ Project?


Leave a Reply