C语言,gcc编译,WSL终端bash
我编写了一个递归函数,用于查找数组中的最小数,效果很好。
/*01*/ int minimo(int array[], int n)
/*02*/ {
/*03*/ static int min = 0;
/*04*/
/*05*/ if (n == N)
/*06*/ {
/*07*/ return array[n-1];
/*08*/ }
/*09*/ else
/*10*/ {
/*11*/ min = minimo(array, n+1);
/*12*/ if(array[n]<min){
/*13*/ min = array[n];
/*14*/ }
/*15*/ }
/*16*/ }
唯一问题是它不应该工作,因为它不会将“min”返回给调用者......
int main()
{
//Var
int array[N] = {10, 2, 5, 1, 7};
printf("Min: %d\n", minimo(array, 0));
}
我的担忧实际上是一个问题,但不是在我的机器上,该功能可以正常工作;
这是我 friend 的笔记本电脑和 IDE 上的一个问题,我尝试在 friend 的 Macbook 上复制到 XCode,但如果“return min;”这一行就无法工作。未在函数末尾添加。
在第 15-16 行之间我必须添加
return min;
/*15*/ }
return min;
/*16*/ }
我的 问题 因为你是以下:
这是我的第一篇文章,如果我违反了任何论坛规则,请多多包涵。
最佳答案
My concern is actually a problem, but not on my machine onto which the function works just fine as it is; it is a problem on my friends' laptops and IDEs, I tried copying to XCode on a friend's Macbook and it wouldn't work if the line "return min;" wasn't added at the end of the function.
未定义行为的典型示例。在一台机器上工作,但不能在另一台机器上工作。白天有效,夜间无效。适用于一个编译器但不适用于另一个编译器。当您调用未定义的行为时,C 标准对代码的行为方式没有任何要求。
C11 standard 6.9.1.12
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
在您的代码中,这正是发生的事情。当您尝试打印返回值时,您会调用未定义的行为。
与许多人认为的相反,完全允许在非 void 函数中省略 return 语句。如果您尝试使用不存在的返回值,它只会变成未定义的行为。
为避免这种情况,请始终至少使用
-Wall -Wextra
进行编译.
关于c - 不带 "return"命令返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60223919/