CS253 Assertions
There are two sorts of assertions in C++:
assert
static_assert
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
assert
assert
for dealing with user errors.
static_assert
static_assert
is like assert
, but:
static_assert
example#include <cassert> static_assert(sizeof(char)==1, "char must be 8 bits"); static_assert(sizeof(int)==3, "int must be 24 bits"); int main() { return 0; }
c.cc:4: error: static assertion failed: int must be 24 bits
Modified: 2017-04-24T11:07 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |