Hosting by Solid Eight Studios,PhotoTangler Collage Maker

This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.


  Use assert()
  Submitted by bgl

Hopefully, most of you will already know and love this technique. However, for those of you still forming good programming habits, read on.

Too many people write code without using assert(). The paranoid ones will put in tests for invalid arguments and return an error code, which no-one then checks for. The sloppy one will just let the code crash, or worse, subtly mis-behave. (Crashing is better because it's usually easier to find than subtle corruption bugs).

The C (and C++) construct "assert()" is found in and can be used to check things that should always be true. It can be used for testing that arguments are OK, for testing that an algorithm indeed returns an item with the right property, and worst case for triggering a known debugger break (by asserting something which is not true).

The good thing about assert() is that it breaks you into the debugger immediately when a bug is detected, where you can look at all the variables, the stack trace, and figure out why it got there. Once you never hit any of your assert()s (and that should, obviously, be the normal state) you can build the release version with #define NDEBUG 1, and all those assert()s will be taken out of the code by the preprocessor, and not suck up cycles checking for bugs in released (thus already debugged) code.

Simple (somewhat silly, not compile-tested) example:

#include <assert.h

struct node { struct node * next; void * item; };

struct node * find_node_for_item(struct node * list, void * item) { assert(list != NULL); /* this function must be called on */ assert(item != NULL); /* valid arguments only */ while (list != NULL) { if (list-item == item) return list; list = list-next; } /* this function should not be called for items that do not exist, so trigger a debugger break */ assert(1 == 0); return NULL; }

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.


Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.