【发布时间】:2018-05-31 00:56:17
【问题描述】:
作为 Stephen Kochan 的“Programming in C”(第 3 版)的建议练习,我想向 strToInt 函数添加一些功能,该函数将字符串转换为整数。如果传递的字符串文字有效(如“123”或“13”),该函数有一个返回类型int。但如果字符串包含任何非数值(例如“12x3”、“foo”),则应打印错误消息并退出函数。由于返回类型为int,因此需要返回一个整数,但在这种情况下,这可能会产生误导。所以我的问题是,在这种情况下应该返回什么,这样返回的值/类型才能明确表明传递了无效的字符串文字并且不能与有效的返回值混淆?
int strToInt(const char string[])
{
int i = 0, intValue, result = 0;
// check whether string passed is a valid literal
while (string[i] != '\0')
{
if (string[i] < '0' || string[i] > '9')
{
printf("ValueError: Invalid literal\n");
return; // what should be returned here?
}
++i;
}
for (i = 0; string[i] >= '0' && string[i] <= '9'; ++i)
{
intValue = string[i] - '0';
result = result * 10 + intValue;
}
return result;
}
【问题讨论】:
标签: c function return return-value return-type