C naming suggestion for Error Code enums

本小妞迷上赌 提交于 2019-11-29 23:21:41
user7116

I'm usually a fan of one set of error returns for an entire library. This way in consumers they don't have to worry about "was the -1 bad input to X or could not connect to Y".

I'm also a fan of E_ prefixes, but really any will do:

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 enum _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" },
    ....
};

I'm of the opinion that is good style. The CMDERR_ prefix groups together the related error codes (assuming they're related to some kind of "command invocation/execution")

Since all of your examples seem to be related to your config functions, I'd just go with a one enum definition using CONFIG_ prefix (or CFG_ for brevity).

enum Config_Errors {
    CONFIG_FILE_NOT_FOUND,
    CONFIG_FILE_EOF_ERROR,
    CONFIG_FILE_OPEN_ERROR,
    //etc.
};

The reasoning behind the common prefix is that when using an enumerated type you want to make it clear that the members of the type all belong to the same group.

The CMDERR_ prefix in the IRC client source code is a good style, but defining enum without any name is not a good style. Not good because you cannot say it is an enum type, only an integer type like below:

CMDERR function1();

int function1(); // actually returning CMDERR unnamed enum

and you cannot define variable using the enum type like below:

CMDERR errResult;

int errResult; // actually errResult is CMDERR unnamed enum
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!