Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Preconditions and domain invariants

Separate caller obligations from valid object state. Validate external input independently of `assert`, and design the type’s public interface to preserve its invariant.

Version: ISO C++23; implementation support may vary

Syntax

// ISO C++23: assert is a macro, not std::assert.
#include <cassert>
assert(condition);
static_assert(constant_condition);
static_assert(constant_condition, "message");

// To disable assert, define NDEBUG before including <cassert>.
// Preconditions and domain invariants are design rules, not C++23 declarations.

The distinction between preconditions and domain invariants is about who guarantees what. A precondition must hold before an operation is used; the caller is responsible for meeting it. For example, limit->get() requires limit to contain a value. A domain invariant describes valid object state: every Limit must store a number from 1 through 100. Construction establishes the invariant, and public operations preserve it.

In C++23, assert(condition) from <cassert> is a macro, not a std::assert function. When enabled, it evaluates the condition; a zero result (including false) writes a diagnostic to standard error and calls std::abort(). If NDEBUG is defined when <cassert> is included, the expression is not evaluated. Do not put external-input validation or required side effects inside assert.

static_assert is a compile-time declaration unaffected by NDEBUG. Here it checks the constant bounds: a false condition makes the program ill-formed. It does not check a value received at run time.

Limit::make checks the range with an ordinary if and returns std::nullopt on rejection. An unchecked public constructor or a writable public field would let callers bypass the factory or invalidate a valid object. The private constructor taking an integer and the private field with no public way to write arbitrary values close those paths. get() returns a copy of the number; its assert only diagnoses an internal bug.

Examples

#include <cassert>
#include <iostream>
#include <optional>

class Limit {
    static constexpr int min_value = 1;
    static constexpr int max_value = 100;
    static_assert(min_value <= max_value);

    int value_;
    explicit Limit(int value) noexcept : value_(value) {}

    static constexpr bool in_range(int value) noexcept {
        return min_value <= value && value <= max_value;
    }

public:
    static std::optional<Limit> make(int value) noexcept {
        if (!in_range(value)) {
            return std::nullopt;
        }
        return Limit{value};
    }

    int get() const noexcept {
        assert(in_range(value_));
        return value_;
    }
};

void report(int input) {
    const auto limit = Limit::make(input);
    if (limit) {
        std::cout << input << ": accepted " << limit->get() << '\n';
    } else {
        std::cout << input << ": rejected\n";
    }
}

int main() {
    report(0);
    report(42);
    report(101);
}

Result

0: rejected
42: accepted 42
101: rejected

The integers `0`, `42`, and `101` stand in for input that has already been read. `if (limit)` checks for a value before using `->`. The expected output is identical with and without `NDEBUG`.

Related lessons

  • C++ · Lesson 52 · Advanced · Version: 3

Sources