Function Contracts
& Invariants
Learn to specify preconditions, postconditions, and invariants so your C++ functions are reliable, testable, and self-documenting.
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.
Why Contracts Matter
The Contract Model Visualized
Formal Definition
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.
How to Write a Function Contract
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
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
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?