I recently heard from
nion and others that "assert() is crap". I would like to object this, and back that assertion (harhar!) with a few facts.
So, why is assert() not crap? Well, assert() is an early predecessor of a concept that is now known as
Design by contract (DBC). The idea of DBC is that the caller of a function and the callee (i.e. the function) place a contract on what function arguments are allowed (the so-called "preconditions") and which return values are allowed (the so-called "postconditions"). In order to check whether both parties meet the contract, these preconditions and postconditions are formulated by the programmer of the callee, and the compiler (if supported by the language) adds code to check these conditions or some support library checks the conditions. If one of the conditions failed, the program fails hard - as one of the parties has violated the contract, - usually by aborting the program. As DBC has its roots in the OO area, a third condition has been added, the so-called "invariant", which checks the internal consistency of the object before leaving the function.
So why use DBC? Because, if implemented properly for all involved functions, it provides a specification on how the function may be called and what return results can be expected. During development, more attention is paid to the code and specification, and during testing, a lot of bugs (not all, such as incorrect specifications and logical errors) can be detected a lot easier than without DBC. Experience with languages like
Eiffel has shown that this way of implementing and debugging code is very efficient, helping the programmer to get a program practically bug-free a lot faster. Of course, as with other techniques, DBC doesn't solve all problems, and one must not solely rely on DBC to find and fix bugs.
Now back to the actual topic, assert(). assert() is a simple mechanism that can help C and C++ programmers to implement simplified variants of DBC. Especially pre- and postconditions are easy to implement with them. So that's why assert() is "not crap", as nion stated. It is a useful tool, can help with debugging and testing and even be disabled when not required anymore.
Last, but not least, the humorous side of engaging this argument:
assert(strcmp("assert()","crap")==0); // leads to "assertion failed"