Tags C & C++

What a great idea, how haven't I thought of it before !

We all know that the assert() macro is a Good Thing (TM). However, not everyone uses it, and many don't really know when to use it. Well, I've just read a great advice from the Embedded magazine...

Consider the following:

// Assumes: arg1 positive, arg2 non-null
void foo(int arg1, char* arg2 ...)

So far so good, right ? This is a good comment: document your assumptions. But there's a much better way !

void foo(int arg1, char* arg2 ...)
    assert(arg1 > 0);

Why is it a better way, you wonder ?
Simple... What if your assumptions change ? Comments are known to be often forgot and discarded when changes take place, but it's harder to forget code. Especially assert() which will let itself known loud and fast if not updated.

Benefits: (1) The code is clearer, comments saved. (2) More immune to changes. (3) What if the assumption fails ? The comments don't protect against that, while assert() does


comments powered by Disqus