Rob said:
In general,
is it considered bad practice to use asserts in production code?
What about writing a macro that does the same as assert
but continues to work regardless of the state of NDEBUG?
Suppose that you are writing a function library
for other C programmers to use with a function
double sqrt(double);
for example,
and your Application Program Interface (API) specifies that
it is a programming error to pass a negative value to sqrt(double).
You can help programmers who use your library
to trap and locate this bug:
#ifndef GUARD_LIBRARY_H
#define GUARD_LIBRARY_H 1
#include<math.h>
inline
double sqrt_error(double x, char* file, int line) {
if (x < 0.0) {
fprintf(stderr, "In file %s: line #%d: "
"argument 1 in function sqrt(double) is negative!",
file, line);
}
return sqrt(x);
}
#ifndef NDEBUG
#define sqrt(x) sqrt_error((x), __FILE__, __LINE__)
#endif//NDEBUG
#endif//GUARD_LIBRARY_H
Unless NDEBUG is defined,
every invocation of sqrt(x) will be replaced
with sqrt_error((x), __FILE__, __LINE__)
and sqrt_error(double, char*, int) will report
the file name and line number where the bug occurred.