01 / 21

C++ Assertions

Learn to use assert to enforce invariants in your programs: catch bugs early, document assumptions, and write more robust code.

C++ Debugging

What Is an Assertion?

An assertion is a statement in your code that declares something you believe must always be true at a particular point during execution. If the condition is false, the program immediately halts with an error message.

✓ True
Program continues normally: nothing happens.
✕ False
Program aborts with a diagnostic message including the file and line.

Understanding Invariants

An invariant is a condition that is expected to be true at a specific point in your program, every time execution reaches that point. Invariants describe the rules your data must follow.

Precondition
Must be true before a function runs: e.g., "the input must be positive."
Postcondition
Must be true after a function returns: e.g., "the result is sorted."
Loop Invariant
Must be true at the start of every iteration of a loop.

Why Assert?

1
Catch bugs early. A failed assertion pinpoints exactly where an assumption was violated, before the error cascades into mysterious behaviour elsewhere.
2
Document your assumptions. Assertions serve as executable documentation: anyone reading the code can see what must be true.
3
Zero cost in production. Assertions can be disabled by defining NDEBUG, so they vanish from release builds.
4
Simplify debugging. The error message includes the failed expression, source file, and line number.

The assert Macro

#include <cassert> // Syntax: assert(boolean_expression);

The assert macro evaluates its argument. If the expression is true (non-zero), nothing happens. If it is false (zero), the program prints a diagnostic and calls abort().

How assert Works

assert(expr) NDEBUG defined? Yes No-op No expr true? True Continue False Print + abort()

assert vs. if-check

assert(expr) if (!expr) { ... }
Purpose Catch programmer errors Handle runtime conditions
In Release Removed (NDEBUG) Always present
On Failure Aborts the program Executes recovery code
Use When "This should never be false" "This might fail at runtime"
Example Negative array index File not found

How to Apply Assertions

1
Identify the invariant. Ask: "What must be true here for the rest of the code to work correctly?"
2
Express it as a boolean. Translate the English rule into a C++ expression: e.g., size > 0.
3
Include the header. Add #include <cassert> at the top of your file.
4
Place the assert. Write assert(expression); exactly where the invariant must hold.
5
Test with a debug build. Compile without -DNDEBUG and run your tests to verify assertions fire on bugs.

Example 1: Precondition

#include <cassert> double squareRoot(double x) { assert(x >= 0.0); // precondition return std::sqrt(x); }

This is a precondition: a condition that must hold at the start of the function. The function's contract says "give me a non-negative number," and the assertion enforces it.

Example 2: Postcondition

#include <cassert> int factorial(int n) { assert(n >= 0); // precondition int result = 1; for (int i = 2; i <= n; ++i) { result *= i; } assert(result >= 1); // postcondition return result; }

Example 3: Loop Invariant

#include <cassert> #include <vector> int binarySearch(const std::vector<int>& v, int target) { int lo = 0, hi = v.size() - 1; while (lo <= hi) { assert(lo >= 0 && hi < (int)v.size()); int mid = lo + (hi - lo) / 2; if (v[mid] == target) return mid; else if (v[mid] < target) lo = mid + 1; else hi = mid - 1; } return -1; }

NDEBUG and Release Builds

Assertions are a debug-only tool. In release (production) builds, you define the macro NDEBUG, which turns every assert into a no-op.

// Compile for debugging (assertions enabled): g++ -g -o myapp main.cpp // Compile for release (assertions disabled): g++ -O2 -DNDEBUG -o myapp main.cpp

The Side-Effect Trap

✕ Wrong
assert(ptr = allocate());
✓ Correct
ptr = allocate();
assert(ptr != nullptr);

Where to Place Assertions

void processOrder(Order& order) { assert(order.isValid()); // Precondition // ... process logic ... assert(items > 0); // Loop invariant assert(order.isProcessed()); // Postcondition } ENTRY BODY EXIT

Place assertions at function entry (preconditions), inside loop bodies (loop invariants), and before return (postconditions). Each one guards a different class of bug.

Common Mistakes

✕ Side Effects Inside assert
Placing assignments or function calls with side effects inside the assertion expression. These vanish with NDEBUG.
✕ Using assert for User Input
Validating user-supplied data with assert instead of proper error handling. User errors are not bugs.
✕ Forgetting <cassert>
Omitting the include causes a compilation error. Always add #include <cassert> when using assert.

Summary Table

Concept Description Example
Precondition Must hold at function entry assert(\(n > 0\))
Postcondition Must hold before return assert(\(result \ge 0\))
Loop Invariant Must hold each iteration assert(\(lo \ge 0 \text{ && } hi < v.size()\))
NDEBUG Disables all assertions -DNDEBUG flag
Side Effects Never inside assert assert(\(x\text{++}\)) is wrong

Question 1 of 5

What happens when an assert expression evaluates to false in a debug build?

Question 2 of 5

Which header must you include to use the assert macro in C++?

Question 3 of 5

What is wrong with the following code?

assert(file.open("data.txt"));

Question 4 of 5

A function requires that its parameter age is between 0 and 150 inclusive. Which assertion correctly enforces this precondition?

Question 5 of 5

Which scenario is the best use case for an assertion?