【发布时间】: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