微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误代码枚举的C命名建议

我正在编写一个简单的解析器来读取配置文件.config.h接口只有三个
它们的主要功能如下,
config_init();
config_dinit();
config_parse();
config_read_value();

我的问题是那些函数会发出不同类型的错误,例如,

config_init() emit,FILE_NOT_FOUND,FILE_EOF_ERROR,FILE_OPEN_ERROR,...
config_dinit() emit,NOT_INIT_ERROR,config_parse() emit,PARSE_ERROR,OVERFLOW_ERROR,INVALID_CHaraCTER_FOUND_ERROR,...
config_read_value() emit,SECTION_NOT_FOUND,KEYWORD_NOT_FOUND,NOT_INITIALIZED_ERROR,INVALID_STATE_ERROR,... etc.

Then I create enums for each function,for by using these names,enum Config_ParseError{...},enum Config_InitError{...},enum Config_ReadValueError{..}
etc.

一些枚举值相互重叠,也会出现“编译错误”.喜欢
溢出错误,

我正在打开你的建议,

我已经对谷歌做了快速研究,发现最受欢迎的IRC客户端
代码定义了这样的枚举,

enum {
    CMDERR_OPTION_UNKNowN = -3,/* unkNown -option */
    CMDERR_OPTION_AMBIGUOUS = -2,/* ambiguous -option */
    CMDERR_OPTION_ARG_MISSING = -1,/* argument missing for -option */

    CMDERR_UNKNowN,/* unkNown command */
    CMDERR_AMBIGUOUS,/* ambiguous command */

        CMDERR_ERRNO,/* get the error from errno */
    CMDERR_NOT_ENOUGH_ParaMS,/* not enough parameters given */
    CMDERR_NOT_CONNECTED,/* not connected to server */
    CMDERR_NOT_JOINED,/* not joined to any channels in this window */
    CMDERR_CHAN_NOT_FOUND,/* channel not found */
    CMDERR_CHAN_NOT_SYNCED,/* channel not fully synchronized yet */
    CMDERR_ILLEgal_PROTO,/* requires different chat protocol than the active server */
    CMDERR_NOT_GOOD_IDEA,/* not good idea to do,-yes overrides this */
    CMDERR_INVALID_TIME,/* invalid time specification */
    CMDERR_INVALID_CHARSET,/* invalid charset specification */
    CMDERR_EVAL_MAX_RECURSE,/* eval hit recursion limit */
    CMDERR_PROGRAM_NOT_FOUND /* program not found */
};

它定义了没有任何名字的枚举,这是一个好的风格吗?那么为什么是什么原因
那?

真的需要一些更好的命名决定.请不要伤害我,我只是
开始阅读“写出漂亮的C代码”一书.

提前致谢.
三墩.

解决方法

我通常是整个库的一组错误返回的粉丝.这种方式在消费者中他们不必担心“输入X的输入是-1还是无法连接到Y”.

我也是E_前缀的粉丝,但实际上任何人都会做:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐