Lesson 190 +10 XP

Assert and static_assert

Assert and static_assert

Asserts are tiny checks that catch bugs the moment they happen. C++ gives you two flavors: assert for runtime debugging and static_assert for compile-time checks.

assert checks at runtime

assert(condition) is a macro; if the condition is false, it fires and aborts the program.

#include <cassert>

double average(int sum, int count) {
    assert(count > 0);   // never divide by zero here
    return (double)sum / count;
}

In debug builds, an assert that fails halts your program on the failing line of code. In correct code, asserts never fire.

Disabling assert with NDEBUG

Defining the NDEBUG macro strips all assert calls out of the build:

#define NDEBUG
#include <cassert>

So asserts run during development but vanish in release, leaving zero overhead.

static_assert at compile time

static_assert requires a constant expression and a message; if it is false, the compiler refuses to build:

static_assert(sizeof(int) >= 4, "int must be at least 4 bytes");

The compiler itself validates your assumption before the program ever runs.

Which one when

  • Use assert() for a runtime invariant: a zero divisor, an out-of-range index.
  • Use static_assert for a compile-time invariant about types and sizes.
  • Asserts document assumptions that must hold; both kinds catch bugs quicker.

TL;DR

  • assert(condition) aborts runtime when the condition is false.
  • Asserts are stripped out when you define NDEBUG.
  • static_assert(cond, "msg") fails at compile time.
  • Use assert for runtime invariants, static_assert for compile-time ones.
  • Both catches bugs the moment they exist.