【发布时间】:2018-10-19 03:33:22
【问题描述】:
运行一个递归函数,例如这个(在 gcc 7.3.1 中编译):
#include <stdio.h>
int arr[] = {5,1,2,6,7,3};
int arraySize = 6;
int recfind(int value, int index)
{
if (arr[index] == value)
return 1;
if (index >= arraySize)
return 0;
// return recfind(value, ++index);
recfind(value, ++index);
}
int main() {
printf("found 6? %d\n", recfind(6, 0));
printf("found 9? %d\n", recfind(9, 0));
}
我得到以下输出:
found 6? 1
found 9? 0
为什么会这样?既然没有返回递归recfind调用的结果,那么高层调用的返回值如何选择呢?
【问题讨论】:
-
函数被指定返回一些东西,但没有。你不知道你怎么能摆脱它吗?不管结果如何?
-
@StoryTeller 是的,这正是我想知道的。
-
试图讨论undefined behavior的行为是没有意义的。
-
您的编译器应该对此发出警告。
标签: c recursion return return-value