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 I assert the divisor be non-zero or should I return an error code? Please give more examples, if you can, to make the distinction clear.
Assertions should be used to check something that should never happen, while an exception should be used to check something that might happen. For example, a function might divide by 0, so an exception should be used, but an assertion could be used to check that the harddrive suddenly disappears.
In the C Programming Language, assert is a macro that is designed to be used like a function. It checks the value of an expression that we expect to be true under normal circumstances. If expression is a nonzero value, the assert macro does nothing.
Assertions are mainly used to check logically impossible situations. For example, they can be used to check the state a code expects before it starts running or the state after it finishes running. Unlike normal exception/error handling, assertions are generally disabled at run-time. Arguments to private methods.
JUnit assertions are intended to be used in test code, but not in production code. Using JUnit assertions outside of test scope may be confusing.
assert
aborts the process, but is turned into a no-op when the program is compiled with -DNDEBUG
, so it's a rather crude debugging tool and nothing more than that. You should only use assert
to check for situations that "can't happen", e.g. that violate the invariants or postconditions of an algorithm, but probably not for input validation (certainly not in libraries). When detecting invalid input from clients, be friendly and return an error code.
An example use of assert
could be: you've implemented an incredibly smart sorting algorithm and you want to check whether it really sorts. Since the sorting function is supposed to "just work" and therefore doesn't return a value, you can't add error returns without changing the API.
void sort(int *a, size_t n) { recursive_super_duper_sort(a, 0, n); assert(is_sorted(a, n)); } static bool is_sorted(int const *a, size_t n) { for (size_t i=0; i<n-1; i++) if (a[i] > a[i+1]) return false; return true; }
In the long run, you'd really want a proper unit testing framework for this kind of thing instead of assert
, but it's useful as a temporary debugging tool.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With