【问题标题】:C - using enums to send error messages to user?C - 使用枚举向用户发送错误消息?
【发布时间】:2020-11-28 23:59:50
【问题描述】:

我在 C 中创建了一个基于数组的 Stack 数据结构。

此外,我想实现错误处理以允许其他人也可以将此类用于自己的用途,但我想出的最好方法是让该方法返回一个枚举,然后让用户将值发送到“printErrorMessage”函数将消息打印到终端。

    /**enum with all the possible error messages**/
    typedef enum stackError_t {SUCESS, FAILED_MEMORY_ALLOCATION, FAILED_STACK_DOUBLEUP, NEGATIVE_VALUE, STACK_EMPTY}STACK_ERROR_MESSAGE;

   /**prints error message to terminal**/
   void printErrorMessage(STACK_ERROR_MESSAGE *message){
      switch(*message){
        case SUCESS : printf("Nothing went wrong!");break;
        case FAILED_MEMORY_ALLOCATION : printf("Not enough memory!");break;
        case FAILED_STACK_DOUBLEUP : printf("Stack has failed to doubleUP!");break;
        case NEGATIVE_VALUE : printf("Negative Value should have not been entered!");break;
        case STACK_EMPTY : break;
    }
    /**example method that can return an error**/
    STACK_ERROR_MESSAGE makeStack(Stack **stack, const uint32_t length, const uint32_t bytes)

另一个是让用户传入一个指向函数的枚举指针

    void * popStack(Stack *stack, STACK_ERROR_MESSAGE *message)

如果出现问题,然后调用“printErrorMessage”函数。

我希望得到更好的想法,然后使用枚举来处理这个错误,因为它看起来有点笨拙。另外,如果堆栈指针已初始化,我需要检查每个方法并添加一个错误枚举,如“STACK_NOT_INITIALIZED”。

TLDR - 还有哪些其他方法可以在 C 中进行错误处理?如果你使用枚举,你会添加什么类型的错误?

如果有人问过这个问题,我提前道歉。

感谢您的宝贵时间。

问候, 匕首

【问题讨论】:

    标签: c error-handling enums


    【解决方案1】:

    您可以创建一个与STACK_ERROR_MESSAGE 枚举对齐的char[][] 数组(字符串 数组),这样每当您遇到错误时,您就可以使用枚举项作为索引访问所需的字符串:

    /**enum with all the possible error messages**/
    typedef enum stackError_t
    {
        SUCCESS,
        FAILED_MEMORY_ALLOCATION,
        FAILED_STACK_DOUBLEUP,
        NEGATIVE_VALUE,
        STACK_EMPTY,
        MAX_STACK_ERROR
    } STACK_ERROR_MESSAGE;
    
    static const char *stackErrorStrings[]
    {
        "SUCCESS",
        "FAILED_MEMORY_ALLOCATION",
        "FAILED_STACK_DOUBLEUP",
        "NEGATIVE_VALUE",
        "STACK_EMPTY",
        "MAX_STACK_ERROR"
    };
    
    /**prints error message to terminal**/
    void printErrorMessage(STACK_ERROR_MESSAGE *message)
    {
        if( message && *message > SUCCESS && *message < MAX_STACK_ERROR){
            printf("Stack failed with error %s\n", stackErrorStrings[*message]);
        }
    }
    

    这种方法主要适用于软件生命周期内误差变化不大的情况,因为枚举和字符串数组必须保持对齐。

    如您所见,它允许对错误消息字符串进行“标准化”(我选择在成功的情况下不打印任何内容)。

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2021-05-29
      • 2018-03-08
      • 2019-01-26
      • 1970-01-01
      • 2016-02-17
      • 2022-11-11
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多