Having spent a few hours refreshing myself with C programming and being influenced by the java programmers in work, I've decided to be a bit more sensible about how I write C code. Armed with the that in mind, I looked around at how people did unit testing to do test driven software development for C.

It turns out that a lot of the frame works are just over engineered packages that rely on automake and autoconf hell to get working properly. I resorted to looking up and refering to The C Programming Language (book), it had reminded me of just using assert.h.

Using assert() is easier than you would expect and people should probably use it a bit more than not using it!

#include <assert.h>
void assert(scalar expression)

If the assertion is true the program will continue, otherwise it will abort. If you wish to turn of the assertions you could just add #define NDEBUG ahead of the #include and the assertions won't be compiled.

Here's an example usage of assert()

#include <stdio.h>
#include <assert.h>

int main(int argc, char **argv) { 
  int i; 
  for (i=5; i>0; i--) {
    fprintf(stdout, "i => %d\n", i); 
  } 
  assert(i > 0); 
  return 0; 
}

The assertion is that i cannot be zero, so the code will fail. This is probably a bad example of how to use assert() but it does demonstrate what it does. I find that I usually just end up using assertions to check that things aren't NULL or to make sure that things are greater than or less than expected values for variables in my code.

Bookmark and Share