C++ Assertions
Learn to use assert to enforce invariants in your programs: catch bugs early, document assumptions, and write more robust code.
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.
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.
Why Assert?
The assert Macro
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 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
size > 0.#include <cassert> at the top of your file.assert(expression); exactly where the invariant must hold.-DNDEBUG and run your tests to verify assertions fire on bugs.Example 1: Precondition
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
Example 3: Loop Invariant
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.
The Side-Effect Trap
assert(ptr != nullptr);
Where to Place Assertions
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
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"));
bool ok = file.open(...); assert(ok);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?