assert() yourself!

This tip submitted by Kevin Lam on 2005-02-07 12:12:10. It has been viewed 119477 times.
Rating of 5.6 with 664 votes

assert(), in < cassert > for C++ or < assert.h > for C, is an excellent feature of the C/C++ programming languages. What it does is help you catch logic errors or improper usage in your code, by testing the expression given to it for truth; if the expression evaluates to false, then it pops up an error message and allows you to debug the program from that point in execution (if you have a just-in-time debugger installed) or else just crash so that you don't have a weird bug hidden somewhere that will bite you later.

For example, if you have a certain pointer that when you reach a given section of code should never be NULL - but either you're worried that you might have screwed up somewhere else so that it will end up NULL anyway, or someone else building on top of your code may accidentally do something to make it NULL, then you could have:
assert(thePtrThatShouldNeverBeNull != NULL);

This will ensure that if something goes wrong, you'll definitely know about it.

Also conveniently, after you're done debugging and you're confident that your code is 100% bug-free and you want a little extra performance, at the top of your code you can do:
#define NDEBUG

This will basically turn all the assert() statements off (become invisible to the compiler but not to you), so they won't affect performance in the final release of your program.

Another trick that I learned from CodePlug here is to create a tool called compile_assert() that will catch certain mistakes at compile-time rather than at runtime. Its uses are fewer so I won't anything more about it here, but it's a neat trick anyway and probably a good one to keep in your bag. I encourage you to take a look at how it's defined and used in CodePlug's code.

More tips

Help your fellow programmers! Add a tip!