I would have preferred to add a comment to the answer to this question
but didn’t have enough points. Consider the following code:
enum _config_error
{
E_SUCCESS = 0,
E_INVALID_INPUT = -1,
E_FILE_NOT_FOUND = -2, /* consider some way of returning the OS error too */
...
};
/* type to provide in your API */
typedef _config_error error_t;
/* use this to provide a perror style method to help consumers out */
struct _errordesc {
int code;
char *message;
} errordesc[] = {
{ E_SUCCESS, "No error" },
{ E_INVALID_INPUT, "Invalid input" },
{ E_FILE_NOT_FOUND, "File not found" },
...
};
How does one lookup the error description from errordesc? I can see two problems with the version I come up with:
/* add E_COUNT = 3 to enum _config_error */
const char *errorstring(error_t errnum)
{
unsigned int i;
for (i = 0; i < E_COUNT; ++i) {
if (errordesc[i].code == errnum) {
return errordesc[i].message;
}
}
return "Can't reach this point";
}
- One does know the enum size and has to manually set
E_COUNTto 3. - One cannot reach the return after the for loop, what to do there?
- Is there a better solution?
E_COUNTfromsizeof(errordesc) / sizeof(struct _errordesc)."Unknown error"or something similar.-errnum.