//C 没有异常:函数返回其工作的结果,
//值本身通过指针传出
typedef enum {
PARSE_OK,
PARSE_EMPTY,
PARSE_NOT_A_NUMBER,
PARSE_OUT_OF_RANGE,
} ParseResult;
//[[nodiscard]](C23):忽略结果时,编译器会给出警告
[[nodiscard]] ParseResult parseAge(const char *text, int *age) {
if (*text == '\0') {
return PARSE_EMPTY;
}
char *end;
long value = strtol(text, &end, 10);
if (*end != '\0') {
return PARSE_NOT_A_NUMBER;
}
if (value < 0 || value > 150) {
return PARSE_OUT_OF_RANGE;
}
*age = (int)value;
return PARSE_OK;
}
const char *resultNames[] = {
[PARSE_OK] = "PARSE_OK",
[PARSE_EMPTY] = "PARSE_EMPTY",
[PARSE_NOT_A_NUMBER] = "PARSE_NOT_A_NUMBER",
[PARSE_OUT_OF_RANGE] = "PARSE_OUT_OF_RANGE",
};
int age = 0;
ParseResult result1 = parseAge("42", &age);
//result1 is PARSE_OK, age is 42
//失败时不会改动该值
ParseResult result2 = parseAge("4x2", &age);
//result2 为 PARSE_NOT_A_NUMBER,而 age 为 42
ParseResult result3 = parseAge("200", &age);
//result3 为 PARSE_OUT_OF_RANGE,而 age 为 42
//调用方在调用后立刻检查结果
if (parseAge("", &age) != PARSE_OK) {
printf("no age given\n");
}
//输出 "no age given"
//标准库也是同样的思路:fopen 和 malloc 返回 nullptr,
//POSIX 函数返回 -1,而 errno 说明原因
printf("result1 is %s\n", resultNames[result1]);
printf("result2 is %s\n", resultNames[result2]);
printf("result3 is %s\n", resultNames[result3]);
printf("age is %d\n", age);