Page 1 of 1

The assert macro

Posted: Wed Jan 11, 2006 1:37 am
by Neo
Isn't the assert() macro a compilation time check only.
What about cases where we need runtime checks of some variables values.
What do we do in those cases.

Re:The assert macro

Posted: Wed Jan 11, 2006 2:23 am
by Candy
Neo wrote: Isn't the assert() macro a compilation time check only.
No.
What about cases where we need runtime checks of some variables values.
What do we do in those cases.
Assert asserts that as the function flow passes that statement that the assertion is true. If it isn't, an error is produced.

If assertions are disabled (#define assert(x,y) /* empty */) they are compiled out and don't affect the code in any way.

Re:The assert macro

Posted: Wed Jan 11, 2006 2:24 am
by durand
The assert macro is a runtime check and compiled into your binary. However, it's designed to be ignored later once all your code has been debugged and tested. You just need to compile with -DNDEBUG. Have a look at the definition:

http://www.opengroup.org/onlinepubs/007908799/xsh/assert.h.html

It's used more to catch programming errors rather than bad situations. For example, passing NULL to a function which should never receive NULL.

assert( param != NULL );

So, in cases of where you need to check some runtime variable values, using assert might not be the correct thing to do. Rather do manual checking then:

Code: Select all

If ( (pid <0) || (pid >= MAX_PID) ) return -1;

Re:The assert macro

Posted: Wed Jan 11, 2006 3:09 am
by Solar
durand is correct.

Note that <assert.h> is unusual in one regard: It is not protected against multiple #includes. <assert.h> checks for the definition of NDEBUG at the point of inclusion. That means:

Code: Select all

#define NDEBUG
#include <assert.h>
disables all assert() statements from there onward, and

Code: Select all

#undef NDEBUG
#include <assert.h>
enables them again.

Of course, the most common use is to set NDEBUG globally in your Makefile when you compile a release version of your code.

@ Candy:

assert() takes only one parameter. If that parameter evaluates false (0), it prints the parameter, file, and line number. Later compilers (C99) can also print the function name.

Re:The assert macro

Posted: Wed Jan 11, 2006 4:39 am
by Candy
Solar wrote: @ Candy:

assert() takes only one parameter. If that parameter evaluates false (0), it prints the parameter, file, and line number. Later compilers (C99) can also print the function name.
If you comply with the C standard in usage of assert. I barely use it (yep, I know I should, but I don't) so I'm not sure about that. The most recent one I've used was iirc in java, where it did have two parameters (condition + textual description).