I'm writing a wrapper for realloc
. For return values, I use this:
typedef enum { SALLOC_OK, SALLOC_OVERFLOW, SALLOC_ALLOCFAIL, ... } salloc_rc;
This is used in a function like this:
salloc_rc salloc(<args>) {
if(blabla) return SALLOC_OVERFLOW;
if(blabla) return SALLOC_ALLOCFAIL;
/* More error codes */
return SALLOC_OK;
}
This is of course not the complete code, but it is enough to demonstrate what I want. So far so good. I can check the return value like this:
if(salloc(a,b) != SALLOC_OK) // Handle error
or if I want to be more precise:
if(salloc(a,b) == SALLOC_OVERFLOW) // Handle overflow
However, I want this to be compatible with the usual way of checking for error. I want to be able to use:
if(!salloc(a,b)) // Handle error
and
if(salloc(a,b) { /* Do stuff */ }
else { /* Handle error */ }
The problem here is that 0 is false, and EVERYTHING else is true. What I want to do seems impossible, but there might be some way around it that I have missed. The only solution I have found so far is to give the function an extra argument with a pointer to a place where I can store the error code, but I want to avoid that if possible.
TL;DR
How to make a function <type> foo()
able to return different error messages depending on what went wrong while still keeping the possibility to check for error in a "traditional" way, like
if (!foo()) exit(EXIT_FAILURE);