Posted January 21, 2011 by Spyros in C/C++ Programming

Use Assert to Catch Logic Programming Errors


The assert macro is a very nice utility for programmers. It may sound complicated, but it is just a small macro that exits the program, giving us some debugging information on where the assertion happened, if a certain condition gets evaluated to false. Therefore :

assert (1 == 0)  // returns false, the program exits
assert (1 == 1)  // returns true, the program keeps running normally

Whenever you know of a certain milestone that has to be met, you can use assert. For instance, if you do not want a certain sum to exceed a value, you just use an assert to catch that programming error, if it ever happens. Now follows a small program to show the assert usage :

#include <assert.h>

void main()
    int x = 0;
    int y = 1;

    assert (x == y);

x does not equal to y and therefore, once this gets executed, we get the following error :

Assertion failed: (x == y), function main, file assert.c, line 8.
Abort trap