C语言中比较优雅的错误定义

时间:2024-10-28 21:04:51
#include <stdio.h> #include <stdlib.h> #define foreach_http_error \ _ (401, "401 error") \ _ (501, "501 error") typedef enum { #define _(sym,string) HTTP_ERROR_##sym, foreach_http_error #undef _ HTTP_N_ERROR, } http_reply_error_t; static char *http_error_strings[] = { #define _(sym,string) string, foreach_http_error #undef _ }; const char *get_error(const int code) { return http_error_strings[code]; } int main() { const char *err = get_error(HTTP_ERROR_401); printf("err string: %s\n", err); getchar(); return 0; }