Eclectic

About programming and maybe more…

Use assert()

Posted by tread on February 21, 2007

Sadly, very few people do.

What it does is notify you if you reached some logically incorrect state -e.g., if a pointer is NULL, you definitely do not want to continue.

Steps:

include <assert.h>

assert (expression);

// if expression evaluates to false, then the program aborts

// expression can be anything, say (if ptr != NULL)

If the expression does evaluate to false, then you get a message like “assert failed in function foo at line x” – rather useful. Better sprinkle all your code with this – anyway, you can turn it off in production executables by adding

#define NDEBUG

in your code. An easier way – one that doesn’t require source modification – is to pass -DNDEBUG as a parameter when compiling the file.

e.g.,

gcc -c test.c -DNDEBUG

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>