我更愿意对 the answer to this question 添加评论但没有足够的积分。考虑以下代码:
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" },
...
};
如何从 errordesc
中查找错误描述?我可以看到我提出的版本有两个问题:
/* 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";
}
- 知道枚举大小并且必须手动将
E_COUNT
设置为 3。 - for循环后无法到达return,怎么办?
- 有更好的解决方案吗?
最佳答案
- 您可以根据
sizeof(errordesc)/sizeof(struct _errordesc)
计算E_COUNT
。 - 如果到达循环末尾,只需返回
“未知错误”
或类似内容。 - 由于您的错误代码似乎是连续的(但为负数),您可以使用
-errnum
直接索引到数组中。
关于c - 将错误代码映射到错误描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423907/