首页 > 解决方案 > 为什么递归函数在 Visual Studio 中有效,即使没有返回值

问题描述

#include <iostream>
using namespace std;

int test(int numb) {
    if (numb == 0) return 0;
    test(numb - 1);
}

int main() {
    cout<<test(10);
}

所以我正在解决一些算法问题。此代码适用于 Visual Studio,但不适用于其他在线 shell。即使没有返回,test() 函数会返回什么?还

#include <iostream>
#include<stdio.h>
using namespace std;

int test(int numb) {
    if (numb == 0) return 0;
    cout<<test(numb - 1)<<endl;
}

int main() {
    cout<<test(10);
}

//result
0
1349009568
1349009568
1349009568
1349009568
1349009568
1349009568
1349009568
1349009568
1349009568
1349009568

号码 1349009568 是什么意思?

标签: c++algorithmvisual-studio

解决方案


您的函数在不返回任何内容时具有未定义的行为。数字 1349009568 没有意义,可能是随机的。对我来说,它显示为 0,并且与此版本具有相同的输出,永远不会返回任何内容。

int test(int numb) {
    if (false) return -1;
}

推荐阅读