CS253: Software Development with C++

Fall 2020

Assertions

Show Lecture.Assertions as a slide show.

CS253 Assertions

Assertion failure!
You’re out of here!

Overview

There are two sorts of assertions in C++:

They both come from <cassert>.

assert()

assert() is a preprocessor macro (!) that is, essentially:

void assert(bool condition) {
    if (!condition) {
        cerr << "assertion failed: ''name-of-condition''\n"
        abort();
    }
}

assert() example

void delete_file(const std::string &fname) {
    assert(!fname.empty());
    remove(fname.c_str());
}

int main() {
    delete_file("tempfile");
    delete_file("");
}
a.out: c.cc:2: void delete_file(const string&): Assertion `!fname.empty()' failed.
SIGABRT: Aborted

When to use assert()

Disabling assertions

If you’re concerned about the run-time cost of assertions:

Avoid side effects

The assert() expression must not have side effects:

% cat ~cs253/Example/assert.cc
#include <iostream>
#include <cassert>

using namespace std;

int main() {
    int n = 42;
    assert(++n > 10);	// 🦡
    cout << n << '\n';
}
% g++ -Wall ~cs253/Example/assert.cc
% ./a.out
43
% g++ -DNDEBUG -Wall ~cs253/Example/assert.cc
% ./a.out
42

static_assert()

static_assert() is like assert(), but:

static_assert() example

static_assert(-1 >> 1 == -1, "right shift must preserve sign");

int main() {
    cout << "Hello, world!\n";
    static_assert(sizeof(short)==2, "short must be 16 bits");
    return 0;
}

static_assert(sizeof(int)==3, "int must be 24 bits");
c.cc:9: error: static assertion failed: int must be 24 bits

static_assert() optional message

static_assert(sizeof(bool)==7, "I need 56-bit booleans!");
c.cc:1: error: static assertion failed: I need 56-bit booleans!

In C++ 2017, the message in static_assert() became optional. Sometimes, it’s just not worth the trouble of writing the verbose error message, and it’s good enough to give a file name and line number so the programmer can look it up themself. It’s a tradeoff between good error messages and code brevity.

static_assert(sizeof(bool)==7);
c.cc:1: error: static assertion failed