Insist on better asserts
Posted Sun, 09 Oct 2011
I never really liked C's assert() feature. If an assertion is violated, it'll
tell you what assertion failed but completely lacks any context:
example: example.c:9: main: Assertion `i == 3' failed.This is better:
Assertion failed insist.c:7 in main(), insist(i == 3): Something went wrong, wanted i == 3, got 4The main difference here is that there's context about what failed. A message for humans looking to debug this. This is especially important on Linux these days because every distro I've used recently hates sysadmins and hates debugging - all libraries are stripped of debug symbols and coredumps are disabled by default.
What's the usage look like?
#includeI also added a special 'return' version of this, 'insist_return' that lets you do error checking and early aborting like this:#include #include "insist.h" int main() { int i = 4; //assert(i == 3); insist(i == 3, "Something went wrong, wanted i == 3, got %d", i); return 0; }
insist_return(fd >= 0, START_FAILURE,
"socket() returned %d, an error: %s", fd, strerror(errno));
Works just like insist() except returns START_FAILURE if 'fd > 0' is false and
additionally logs the error formatted above.
Code here: insist.h