我的Herb Schildt关于C++的书说:"......在C++中,如果函数被声明为返回一个值,它必须返回一个值." 但是,如果我编写一个非void返回类型的函数并且不返回任何内容,则编译器会发出警告而不是错误:"控件到达非void函数的结尾".
我使用gcc(MinGW)并设置了-pedantic标志.
在查看工作代码时,我发现了一些(看似)令人反感的代码,其中函数具有返回类型,但没有返回.我知道代码有效,但认为它只是编译器中的一个错误.
我编写了以下测试并使用我的编译器运行它(gcc(Homebrew gcc 5.2.0)5.2.0)
#include <stdio.h>
int f(int a, int b) {
int c = a + b;
}
int main() {
int x = 5, y = 6;
printf("f(%d,%d) is %d\n", x, y, f(x,y)); // f(5,6) is 11
return 0;
}
Run Code Online (Sandbox Code Playgroud)
类似于我在工作中发现的代码,这默认返回函数中执行的最后一个表达式的结果.
我发现了这个问题,但对答案不满意.我知道-Wall -Werror可以避免这种行为,但为什么它是一个选项呢?为什么这仍然允许?
运行这样的递归函数(在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));
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
found 6? 1
found 9? 0
Run Code Online (Sandbox Code Playgroud)
为什么这样做?由于recfind未返回递归调用的结果,所以如何选择更高级别调用的返回值?
如果问题已经问过,请随意将此帖子作为重复,我还没有找到与此相同的帖子
据我所知,没有必要return在void 函数中,例如:
void ex () {printf ("Hi\n");}
Run Code Online (Sandbox Code Playgroud)
但是,是不是很好,如果没有return一个void 递归?我在想的是,程序会一直调用func (num-1)直到它到达0并返回,所以它不会打印0到输出,我需要return在函数的末尾,所以在递归调用完成后,你回到以前的func ()直接呼叫者。
这是代码,
#include <stdio.h>
void func (int num)
{
if (!num) return;
func (num-1);
printf ("%d\n", num);
return; //Is it necessary to put return here?
}
int main ()
{
func (10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出,
1
2
3
4
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)
没有 last return,它也可以正常工作,还是我错过了什么?