1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| #define ERROR_CODES(X) \ X(SUCCESS, 0, "操作成功") \ X(NULL_POINTER, 1, "空指针错误") \ X(OUT_OF_MEMORY, 2, "内存不足") \ X(INVALID_ARGUMENT, 3, "无效参数") \ X(FILE_NOT_FOUND, 4, "文件未找到")
#define GENERATE_ENUM(name, value, desc) name = value, typedef enum { ERROR_CODES(GENERATE_ENUM) } ErrorCode; #undef GENERATE_ENUM
#define GENERATE_STRING(name, value, desc) desc, static const char* error_messages[] = { ERROR_CODES(GENERATE_STRING) }; #undef GENERATE_STRING
#define GENERATE_CASE(name, value, desc) \ case name: return desc;
const char* get_error_message(ErrorCode code) { switch (code) { ERROR_CODES(GENERATE_CASE) default: return "未知错误"; } } #undef GENERATE_CASE
int main() { for (int i = 0; i < 5; i++) { printf("错误码 %d: %s\n", i, get_error_message(i)); } return 0; }
|