tags:

views:

28

answers:

1

I'm writing C89 on MSFT Visual Studio 2010 Beta. How can I make an assertion, similar to Java's assert keyword? I think I need to define a macro, but I'm not sure how. (It seems like this is something that's been done before, so I'd rather use that than try to roll my own.)

Here's a guess:

int assert(int truth_value) {
   // crash the program with an appropriate error message   
}
+1  A: 

C89 has <assert.h>, which contains the macro you're looking for.

#include <assert.h>
assert(expression);

From the documentation:

The assert() macro tests the given expression and if it is false, the calling process is terminated. A diagnostic message is written to stderr and the abort(3) function is called, effectively terminating the program.

If expression is true, the assert() macro does nothing.

Carl Norum
Yup. The thing to remember is that `assert()` is usually disabled for production runs, so it's important to make sure *expression* has no effects other than returning a true or false value.
David Thornley
Yeah, you can disable `assert()` by defining `NDEBUG`.
Carl Norum