【发布时间】:2019-03-04 19:53:07
【问题描述】:
我有一个函数,它以 char 数组的形式接受数学运算,返回一个 int 结果(这一切都有效,纯粹是为了上下文,与问题无关)。
当然,我的函数定义是:int calc(char* operation) {},它期望返回一个 int。
在解析字符串以确定操作数和要执行的操作后,我将结果分配给一个变量。我刚刚意识到我忘记将 return 语句放在函数中,但我仍然得到正确的结果......
这里是函数。我原来忘记了最后一行。
// Function to return int results of operation specified in char* (argv[1])
int calc(char* operation)
{
int op_index = 0;
int end_index = 0;
for (int i = 0; i < 128; i ++)
{
if ((operation[i] < 48 || operation[i] > 57) && op_index == 0)
op_index = i;
if (operation[i] == '\0')
{
end_index = i;
i = 128;
}
}
int opa = 0;
int opb = 0;
for (int i = 0; i < op_index; i ++)
opa += (operation[i]-48)*power(10, op_index - (i+1));
for (int i = op_index+1; i < end_index; i ++)
opb += (operation[i]-48)*power(10, end_index - (i+1));
int res = 0;
if (operation[op_index] == '+')
res = opa + opb;
else if (operation[op_index] == '-')
res = opa - opb;
else if (operation[op_index] == '*')
res = opa * opb;
else if (operation[op_index] == '/')
res = opa / opb;
else if (operation[op_index] == '%')
res = opa % opb;
// This is the line that I had forgotten... but still got the right results when calling this function
return res;
}
有人对此有解释吗?我的猜测是它默认返回最后一个函数调用的结果,由于最终语句的 if/else 结构,这将是正确的。
谢谢!
【问题讨论】:
-
在非 void 函数的某个路径上没有
return是未定义的行为。 -
对于未定义的行为,很难说出为什么会这样,因为它取决于您的特定编译器和机器。重要的是要理解在以后的调用中不能依赖这种行为。如果您好奇并想深入挖掘,您可能可以通过查看此函数的程序集获得一些见解。
-
如果您不知道输入字符串的大小,最好使用
(size_t n, char operation[n])而不是(char *operation),如果您在编译时知道它,最好使用(char (*operation)[N])。第一种方法告诉您输入缓冲区的大小。第二个更强大,因为如果输入缓冲区的大小不同,它就不会编译,因此更安全,但只有在编译时知道数组大小时才会如此。另外由于后者不是数组,而是指向数组的指针,所以用法会有所不同。 -
一个简单的观点是调用和返回是通过将参数压入调用堆栈,然后将结果从调用堆栈中弹出来实现的。因为您在
calc函数中省略了return语句,在调用函数要查找的位置的调用堆栈中没有任何内容。所以,当调用函数出栈寻找结果时,结果发现栈上的数据恰好是你声明的最后一个变量,在本例中是res。但是,它可能是其他一些变量,或者您可能会在访问不可用的信息时崩溃
标签: c return return-value return-type