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.
I am writing a function in C. As a matter of style, when is
Share
assertaborts 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 useassertto 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
assertcould 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.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.