Assertions behave differently depending on the language. In C, they are often used incorrectly, and the incorrect usage is so common that many advise that they not be used at all. They should not be used in production (ie, production compiles of C should define NDEBUG
for the preprocessor) as they only serve to slow down execution.
The purpose of an assertion is to state a logical necessity, not to check a result. For example it is correct (in C) to write:
f = malloc( s );
if( f == NULL ) {
...; exit( 1 );
}
assert( f != NULL ); # This is logically necessary.
But completely wrong to ever write:
f = malloc( x ); # THIS IS AN EXAMPLE OF INCORRECT USAGE
assert( f != NULL ); # DO NOT DO THIS
This is actually useful, since it is perfectly valid to write:
f = xmalloc( x );
assert( f != NULL );
Which acts as documentation to the reader that xmalloc is defined in such a way that it will never return a null value.
They are often used at the start of functions:
void f( void *p ) { assert( p != NULL ); ... }
Such usage is not an error check. Rather it serves to indicate that the function f
expects that it will never be passed a null pointer. It is documentation to developers that passing a null pointer to f
is a programming error. Making it an assertion enables the error to be detected at run time when assertions are enabled.