CS253: Software Development with C++

Spring 2018

Assertions

See this page as a slide show

Assertions

CS253 Assertions

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

#include <cassert>
#include <string>

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:5: void delete_file(const string&): Assertion `!fname.empty()' failed.
SIGABRT: Aborted

When to use assert

static_assert

static_assert is like assert, but:

static_assert example

#include <iostream>
#include <cassert>

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

int main() {
    std::cout << "Hello, world!\n";
    static_assert(sizeof(char)==1, "char must be 8 bits");
    return 0;
}

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

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-19T12:30

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building