Den torsdagen den 15:e maj 2014 kl. 12:33:43 UTC+2 skrev Malcolm McLean:
What kind of strategy is good with respect to checking if a function call was successful or not?
There are two sorts of functions, function that do IO, and functions that shuffle bits about
in the computer memory. (In normal English usage, the first are "procedures", the second "functions",
but C calls both "functions", because the compiler isn't set up to make a rigorous distinction
between them.
Now an IO function can always fail if the IO device fails in some way.
A bit shuffling function can only fail if there is an internal programming error, if there is an external
programming error (it's called with invalid arguments), or if it runs out of memory - a call to
malloc() return null.
If there's a programming error, there's no correct behaviour, by definition. So what you do depends
on the stage of development and the environment - are wrong results better or worse than no
results? If you're programming a video game, probably just accept the error and hope that the
player doesn't notice a glitch. If you're programming a life support system, is shutting down the
program more or less catastrophic than blowing a fuse?
However there's a special case. A parser type function. This fails if fed invalid syntax, which might
well be a programming error. But often checking that the input is valid is almost as difficult as
writing the parser itself. So you generally need to consider parse errors specially.
When writing new functions, is it good practice to always have a return value which indicates
if the function call completed successfully or not? This would mean that void return type
should never be used.
It doesn't matter much whether you return an error flag with return error_status; or set a
passed-in error flag with *error = error_status. I tend to prefer the second, but that's just
my own style.
If the function can fail, it makes sense to report that to the caller. What if it's a bit-shuffling
function that doesn't allocate any memory? You could argue that you should return an error
which is always 0, so that if you change the internals for some reason you can expand it.
Other people would say that the extra clutter in the interface isn't worth it.
Should the return value of a function call always be checked to see if it the function call
completed successfully or not?
No, because you can't always handle an error sensibly. Sometimes errors are so unlikely that
there's a much higher chance that the computer will break, then you've got to ask if it's
worth checking the error.
A practical consideration is that C doesn't have exceptions. If every call is followed by an
error check, the error checks dominate the visual layout of the code, and it becomes hard
to see if the non-error logic flow is correct.