If I have a function that returns some sort of pointer, I check for errors by setting the return to NULL on error.
char *foo(void) {
//If stuff doesn't go okay
return NULL;
}
char *bar = foo();
if(!bar) return 1;
This works great because I know in such cases that I will never intend to return NULL.
However, sometimes I will have functions that return integers (In this case, I am reading ints from a configuration file). However, the problem is that there is now no way to check the returned value for errors because any value (including 0) might be genuine.
A couple of workarounds:
- Include an error code parameter in the function
- Return an error code and include an int pointer as a parameter
The problem with both of these is that I have a set of functions that all do the same thing but for different types and I want to maintain a regular interface so that they can be used in the same way.
Is there another solution that doesn't involve changing the interface to the function? What is the most common way of dealing with this situation?
CHOSEN SOLUTION
Thank you for all your thoughts and answers on this.
In the end I decided that if a function is intended to return some data, an error can only be returned through an error parameter. Otherwise, the error is returned directly.
I chose this root because generally I found that when returning more complex forms of data, the number of potential errors were almost always greater than 1. This meant that using NULL as the only source of error data was impractical anyway as it meant there was no way to determine what the error actually was. With functions returning data as an int, it also became impossible to distinguish multiple different error codes from valid data.
The same is not true, of course, for functions that aren't really returning any data in which case I am free to 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.