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();
}
}
- It’s a runtime condition.
- It has to be in executable code.
- What would be a place that’s not in executable code?
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
- Do not use
assert
for dealing with user errors.
- Only use it for “impossible” circumstances:
- Make sure that a function argument, representing a size, is positive.
- Make sure that a pointer argument isn’t null.
- etc.
static_assert
static_assert
is like assert
, but:
- It’s a compile-time test. It “executes” at compile time.
- It fails like a syntax error fails.
- It doesn’t have to be in executable code.
- might be in a class definition
- might be outside of any function or class
- It takes two arguments:
- a condition
- an error message string (optional starting in C++17)
static_assert
example
#include <iostream>
#include <cassert>
static_assert(-1 >> 1 == -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: error: static assertion failed: int must be 24 bits