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
An error code signals runtime behaviour. An assertion is a debugging tool that allows the developer to assert that their assumptions about the program logic are indeed true.
They're two completely different things with different applications.
Error codes are part of your normal program flow. Assertions are only for debugging, and if an assertion is triggered, that means that your program is not written correctly.
Use an assert when your program meets a situation that does not allow to continue. Assertions are a 'contract' and I use them as a 'contract' with OS and situation 'danger in delay'.
In order to emulate exceptions you can still use GOTO 'ERRORLABEL' and terminate clean after running a clean up function.
First, assert
from the <assert.h>
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.