Search⌘ K
AI Features

Testing with assert

Explore how to use the assert macro in C++ to implement defensive programming by detecting logic errors and invalid assumptions. Understand design by contract principles like preconditions and postconditions, and learn when to use assertions versus exceptions. This lesson helps you write safer, more robust code by failing fast during development to identify bugs promptly.

Bugs are often subtle and difficult to diagnose. In some cases, a program may continue running for a long time in a corrupted state before eventually crashing, making the original cause extremely hard to identify. To prevent this, we aim to fail fast.

Failing fast means deliberately stopping execution as soon as a fundamental assumption is violated, such as an index becoming negative, a pointer unexpectedly being null, or an invariant no longer holding. By terminating the program at the moment the error occurs, we are directed immediately to the exact location where the logic first broke down.

This approach is known as defensive programming, and C++ provides a simple, built-in mechanism to support it.

The assertion mechanism

The assert() macro, defined in the <cassert> header, provides a simple way to verify that a condition holds true at a specific point in the program. It evaluates a boolean expression and behaves as follows:

  • If the expression is true: ...