Function Contracts
& Invariants

Learn to specify preconditions, postconditions, and invariants so your C++ functions are reliable, testable, and self-documenting.

C++

What Is a Function Contract?

A function contract is an agreement between the function and its caller. It spells out exactly what the function requires before it runs and what it guarantees after it finishes.

Precondition
What must be true before the function is called: valid inputs, object state, etc.
Postcondition
What the function guarantees when it returns: output properties, side-effects performed.

Why Contracts Matter

1
Catch bugs early: A violated precondition signals a caller error instantly, before data corruption spreads.
2
Self-documenting code: Contracts tell the next developer exactly how to use the function without reading its body.
3
Easier testing: Each pre/postcondition becomes a natural test case boundary.
4
Safer refactoring: Changing a function's internals is safe as long as the contract still holds.

The Contract Model Visualized

Caller provides inputs PRE
\( n > 0 \)
\( \text{vec} \ne \text{nullptr} \)
must hold Function body runs INVARIANT holds throughout POST
\( \text{result} \ge 0 \)
\( \text{sorted} = \text{true} \)
guaranteed

Formal Definition

Precondition
A boolean predicate \( P(x) \) over the inputs that must be true when the function is called.
Postcondition
A boolean predicate \( Q(x, r) \) over inputs and return value that must be true when the function returns.
Invariant
A predicate \( I(s) \) over program state that remains true before and after every operation in a scope.

Expressing Contracts in C++

C++ doesn't have built-in contract syntax (yet). We use comments, assert(), and documentation to encode contracts.

// Precondition:  0 < n <= v.size()
// Postcondition: returns the average of the first n elements
//                result is in range [min_elem, max_elem]
double average(const std::vector<double>& v, int n) {
    assert(n > 0 && "n must be positive");
    assert(static_cast<size_t>(n) <= v.size() && "n exceeds vector size");

    double sum = 0.0;
    for (int i = 0; i < n; ++i)
        sum += v[i];
    return sum / n;
}

Preconditions vs Postconditions vs Invariants

Precondition Postcondition Invariant
When checked Before function runs After function returns Before & after every operation
Whose job? Caller's Function's Both
Example \( \text{index} < \text{size} \) \( \text{result} \ge 0 \) \( \text{size} \ge 0 \text{ always} \)
If violated Caller has a bug Function has a bug Design is broken

Understanding Invariants

An invariant is a condition that stays true throughout the lifetime of a scope: a loop, a class, or an entire program. It anchors your reasoning about correctness.

Loop Invariant
True before the loop starts, true after each iteration, and true when the loop ends.
Class Invariant
True after construction, maintained by every public method, true before destruction.

How to Write a Function Contract

1
Identify all parameters and their types. List every input, including implicit ones like the object's state.
2
State preconditions. Ask: "What must be true for this function to work correctly?" Write each as a boolean expression.
3
State postconditions. Ask: "What does the caller get back? What side-effects occur?" Describe the return value and any modified state.
4
Identify invariants. Ask: "What property must never break?" For loops, describe what stays true each iteration.
5
Encode them in code. Use comments above the function and assert() statements inside it.

Example 1: Binary Search

// Precondition:  vec is sorted in non-decreasing order
//                0 <= lo <= hi <= vec.size()
// Postcondition: returns index of target, or -1 if not found
// Loop invariant: if target exists, it is in vec[lo..hi)
int binarySearch(const std::vector<int>& vec,
                  int target,
                  int lo, int hi) {
    assert(lo >= 0 && hi <= (int)vec.size());
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        // Invariant: target in vec[lo..hi) if it exists
        if (vec[mid] == target) return mid;
        else if (vec[mid] < target) lo = mid + 1;
        else hi = mid;
    }
    return -1;
}

Example 2: Withdraw from Account

class BankAccount {
    double balance_;  // Class invariant: balance_ >= 0
public:
    // Precondition:  amount > 0 && amount <= balance_
    // Postcondition: balance_ decreased by amount
    //                balance_ >= 0 (invariant preserved)
    void withdraw(double amount) {
        assert(amount > 0);
        assert(amount <= balance_);
        balance_ -= amount;
        assert(balance_ >= 0);  // postcondition check
    }
};

Example 3: Factorial with Full Contract

// Precondition:  n >= 0 && n <= 20 (avoid overflow)
// Postcondition: returns n! (n factorial)
// Loop invariant: result == (i-1)! at the start of each iteration
long long factorial(int n) {
    assert(n >= 0 && n <= 20);
    long long result = 1;
    for (int i = 1; i <= n; ++i) {
        // Invariant: result == (i-1)!
        result *= i;
        // Now: result == i!
    }
    assert(result >= 1);  // postcondition: n! >= 1
    return result;
}

Loop Invariant Lifecycle

Initialization Invariant holds? ✓ condition? true Loop Body re-check false Invariant ✓ Post holds ✓

assert() vs Exceptions

assert() Exceptions
Purpose Catch programmer errors Handle runtime failures
Active in release? No (disabled by NDEBUG) Yes
Recovery possible? No (aborts) Yes (catch block)
Use for Preconditions, invariants File not found, bad input
Performance cost Zero in release Small overhead

Common Mistakes

✕ No Contract at All
Writing functions with no comments about what inputs are valid leads to mystery bugs and wasted debugging time.
✕ Weak Precondition
Saying "n should be reasonable" instead of \( n > 0 \land n \le \text{size()} \). Vague conditions are useless for testing.
✕ Side-Effects in assert()
Writing assert(resource.release()) puts real logic inside the assert. In release mode, that code vanishes and the program breaks.
✕ Confusing Pre and Post
Checking the postcondition before the function runs, or checking the precondition after. The order matters.
✕ Breaking the Invariant
A method temporarily invalidates a class invariant and forgets to restore it before returning.

Question 1 of 5

A function has the comment: "Precondition: \( \text{index} < \text{vec.size()} \)". Whose responsibility is it to ensure this condition holds?

Question 2 of 5

Which of the following is a postcondition for a sorting function?

Question 3 of 5

In a binary search loop, the loop invariant states: "if the target exists, it is in \( \text{vec}[\text{lo}..\text{hi}) \)." When is this invariant checked?

Question 4 of 5

What is wrong with writing assert(file.close()) to check that a file closed successfully?

Question 5 of 5

A BankAccount class has the invariant: \( \text{balance} \ge 0 \). The withdraw method subtracts an amount. Which precondition preserves the invariant?