If I have a function that returns some kind of pointer, I check for errors by setting the error to return NULL on error.
char *foo(void) {
This works fine because I know in such cases that I'm never going to return NULL.
However, sometimes I will have functions that return integers (in this case, I read ints from the configuration file). However, the problem is that now there is no way to check the return value for errors, because any value (including 0) can be genuine.
A few workarounds:
- Include error code parameter in function
- Returns an error code and includes an int pointer as a parameter
The problem with both of them is that I have a set of functions that all do the same thing, but for different types, and I want to support a normal interface so that they can be used the same way.
Is there any other solution that is not related to changing the interface to the function? What is the most common way to deal with this situation?
SELECTION OF DECISION
Thanks for all your thoughts and answers to this.
In the end, I decided that if the function is designed to return some data, the error can only be returned through the error parameter. Otherwise, the error is returned directly.
I chose this root because, as a rule, I found that when returning more complex data forms, the number of potential errors was almost always greater than 1. This meant that using NULL as the sole source of error data was impractical, as it did not mean no way to determine what was actually a mistake. With functions returning data as int, it has also become impossible to distinguish several different error codes from valid data.
The same is not true, of course, for functions that do not actually return any data, in which case I can use the return value as an error code.
I also like the fact that the above pattern makes a clear distinction between functions that return data and functions that don't.
c error-handling
Rupert madden-abbott
source share