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
Here's a real-world example of an assertion I wrote yesterday.
I had two parallel arrays -- let's call them a and b -- and I was about to run an index i from 0 up to the size of a, and then do something with a[i] and b[i]. But if there were fewer elements in b than in a, my code would have an array bounds violation on b. But other parts of the code are supposed to keep the sizes of a and b identical. So I put an assertion before the loop, asserting that the sizes of a and b were equal.
The sizes should be equal -- but if somehow they're not, I want the code to fail on the assertion that tells me why, rather than failing strangely on the Undefined Behavior that would result when I tried to read beyond the end of array b, if it were smaller.