making assert(0) more informative

If you are like me, you use assert all over the place. Even when compiled out, it serves are useful documentation as to what is going on (or what is supposed to be going on).  I recently learned a trick that I could have been using for the past 30 years, even when I first met C in the early 1980s.

Consider when you have an enumerated type, passed to a switch statement

switch (value)
{
case tag1:
    blah blah
case tag2:
    yada yada
...
default:
    /* the value should always be one of the enum tags */
    assert(0);
}

This is all well and good, but when the assert fails, the error message is not particularly useful.

fubar.c: 13: Assertion '0' failed.

Instead, try replacing the comment and the assert with this single assert:

assert(!"the value should always be one of the enum tags");

and now the comment text will be included in the output of the error message, when the assert fails.

fubar.c: 13: Assertion '!"the value should always be one of the enum tags"' failed.

The trick works because, while a string constant is always true in C, it is immediately inverted by the ! operator.  The result is an expression that is always false, but when string-ified still includes the text.

This is useful anywhere and everywhere you are tempted to write assert(0) or, post-C99, assert(false).

But wait, there’s more!