C++ · Module 15 · Lesson 52 min read

assert, static_assert & Debugging

assert (<cassert>) — runtime checks for programmer errors

arduino
assert(index < size && "index out of range");
  • If the condition is false: prints file, line and condition, then aborts
  • Removed completely when compiled with -DNDEBUG (release builds) → zero cost in production
  • Use for bugs (things that should be impossible), NOT for user input or file errors
  • ⚠️ Never put side effects inside: assert(save_file()); disappears in release builds!

static_assert — compile-time checks

c
static_assert(sizeof(long long) == 8, "need 64-bit long long");
static_assert(std::is_nothrow_move_constructible_v<Expense>);

Fails the build if false. Great for assumptions about types, sizes and constants.

Contracts in practice

  • Preconditions: what must be true when a function starts (assert at the top)
  • Postconditions: what's true when it ends
  • Invariants: what's always true for an object (check in a private check_invariants() helper)

Debugging tools

ToolUse
Debugger (gdb, lldb, Visual Studio, VS Code)breakpoints, step over/into/out, watch variables, call stack
Compile with -g -O0accurate line info, no optimizations confusing the debugger
Sanitizers (-fsanitize=address,undefined)memory and UB bugs (lesson 11.5)
Logging to std::cerrquick tracing
std::source_location (C++20)function name / line in log messages without macros
std::stacktrace (C++23)print the call stack

gdb quick start

arduino
g++ -g -O0 app.cpp -o app
gdb ./app
(gdb) break main.cpp:42     (gdb) run
(gdb) next / step / finish  (gdb) print balance
(gdb) backtrace             (gdb) continue

A debugging process

  1. Reproduce reliably (smallest input that fails)
  2. Read the error/assert/sanitizer message carefully
  3. Hypothesize, then check with a breakpoint or a log
  4. Fix the cause, not the symptom
  5. Add a test (or an assert) so it can't come back

Example

C++
#include <cassert>
#include <iostream>
#include <source_location>
#include <string_view>
#include <type_traits>
#include <vector>

void log(std::string_view msg, std::source_location loc = std::source_location::current()) {
    std::cerr << "[" << loc.function_name() << ":" << loc.line() << "] " << msg << '\n';
}

class Budget {
public:
    Budget(double limit) : limit_(limit) {
        assert(limit > 0 && "budget limit must be positive");      // precondition
    }
    void spend(double amount) {
        assert(amount > 0);                                          // precondition (programmer error)
        spent_ += amount;
        check_invariants();
    }
    double remaining() const { return limit_ - spent_; }
private:
    void check_invariants() const { assert(spent_ >= 0 && limit_ > 0); }
    double limit_;
    double spent_ = 0;
};

double average(const std::vector<double>& v) {
    assert(!v.empty() && "average of an empty vector");
    double sum = 0;
    for (double x : v) sum += x;
    return sum / static_cast<double>(v.size());
}

struct Expense { double amount; int day; };
static_assert(sizeof(long long) == 8, "this code assumes 64-bit long long");
static_assert(std::is_trivially_copyable_v<Expense>, "Expense must stay trivially copyable for fast saving");

int main() {
    Budget b(5000);
    b.spend(1200);
    b.spend(300);
    std::cout << "remaining: " << b.remaining() << '\n';
    log("budget updated");

    std::cout << "average: " << average({ 450, 1200, 300 }) << '\n';

#ifdef NDEBUG
    std::cout << "release build: asserts are disabled\n";
#else
    std::cout << "debug build: asserts are active\n";
#endif
    // average({});     // would abort with: Assertion `!v.empty() && "average of an empty vector"' failed.
    return 0;
}

/* Output:
remaining: 3500
average: 650
debug build: asserts are active
*/