I am writing a function in C. As a matter of style, when is it good to use assert compared to returning an error code. Lets say the function is dividing two numbers. Should
First, assert
from the
header can be disabled (e.g. by compiling with gcc -DNDEBUG
), and sometimes is disabled for the "production" version of a binary.
Second, as stated by Linux man page,
The purpose of this macro is to help the programmer find bugs in his
program. The message "assertion failed in file foo.c, function
do_bar(), line 1287" is of no help at all to a user.
So assert should fail only in buggy situations. In exceptional or error situations, you should do something else.
Some tools (or even compilers) might use assert
-ions to e.g. optimize your code.
In your example of a quotient
function, you'll use assert
if, inside your entire program, you are sure that the divisor should be non-zero (but then it could make sense to name the function differently, perhaps quotient_by_non_zero
). If you consider that it could happen, make it a fatal message, an exception (i.e. longjmp
in C), an error code, etc.