The frequent use of assert() is a good thing

I am a big believer of using the assert() macro in C code.

assert() helps debug code, and also self documents code by stating preconditions explicity that would otherwise require inline documentation.  I suggest that all functions have a series of assertions in the prologue, to state exactly what is required.

 Simple assertions for example are in the case of pointers not being NULL.  Another tip to follow is assigning NULL to pointers that are no longer in use. 

When the code is ready for production, the NDEBUG macro can be defined, which means the assert macro evaluates to nothing.  This eliminates any performance penalties.  It can be equally useful to leave the asserts functional if performance is not critical.

One response to “The frequent use of assert() is a good thing

  1. A small tip to the other readers:
    assert in visual studio, disappears on release builds so no source code changes are required for that IDE. (I have tested it in C++ and C#)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s