Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Verify

5.00/5 (1 vote)
2 Jul 2013BSD2 min read 20K   131  
A Practical Alternative to Assert in C++

Background

I confess that in the past, I have abused assert(). I used it for handling nearly all of my errors, and rarely used return values or anything else. When I started taking computer science classes, I was introduced to try, catch, and exceptions, and using them I was able to write more productive and useful code.

However, there is one thing that I believe assert is superior at: aesthetics. When writing code, I much prefer the brevity of the assert macro. It's simpler, takes up less space, and is overall much more pleasing to look at than if statements and throws.

Verify was my solution. A macro which has the brevity of assert, but uses the much more practical Exceptions.

Using the Code

Verify is a two parameter macro. The first parameter is the condition to test, the second is the Exception that will be thrown if the condition is false.

C++
#include "verify.h"

void func1(void* ptr)
{
    verify(ptr != NULL, -1);
}

Verify has three modes:

Standard

The simplest mode, if the condition is false, it throws the Exception. The End.

Debug

Debug mode carries over some features I found useful in the assert macro. If the condition is true, then nothing happens, but if it is false, it prints out the following debug information to the screen:

  • The condition passed to the macro.
  • The exception that was thrown.
  • File name
  • Function name
  • Line number

Then it throws the Exception.

No Verify

The equivalent of NDEBUG for assert. If NVERIFY is defined ahead of the verify header, then verify() has no effect.

Conclusion

And that's pretty much it. Short, sweet, and to the point. If you can think of any improvements or find any problems, please let me know in the comments.

I'd like to thank Charles Nicholson for his article Adventures in Assert, which was a great help in solving several bugs I had in my original code.

License

This article, along with any associated source code and files, is licensed under The BSD License