递归函数错误Dev-C++

Ron*_*ing 0 c++ algorithm recursion dev-c++ visual-c++

我有以下代码顺序搜索在Visual C++中完美运行

#include<iostream>
using namespace std;

int seqSearch(int list[], int length, int item)
{
    int index = length-1;
    if (index < 0)
        return -1;
    if (list[index] == item)
        return (index);
    else seqSearch(list, index, item);
} // end seqSearch

int main () 
{

    int const length = 10;
    int item;
    int list[10] = { 2, 3, 4, 5, 20, 40, 80, 45, 99, 0};

    cout << "Please enter the value to be searched: ";
    cin>> item;

    if (seqSearch(list, length, item) == -1) cout << "Item not found." << endl;
    else cout <<"Item found at position: " << seqSearch(list, length, item) << " of list *Note: (first index of list start at 0)" << endl;

    system("pause");
    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

但是在Dev-C++中它始终显示结果0,我试图调试并看到索引是正确的,但为什么它显示0?为什么我们在VC++和Dev-C++之间存在这种差异?

Vik*_*kas 5

该函数int seqSearch有一个代码路径,else seqSearch(list, index, item);不返回任何内容.改变这个else return seqSearch(list, index, item);应该解决问题.

现在深挖一点.

n2960起草:

§6.6.3/ 2

流出函数末尾相当于没有值的返回; 这会导致值返回函数中的未定义行为.

因此,根据标准,它是一种未定义的行为.

深入挖掘:

  • 为什么不从非void函数返回而不是编译器错误?

检查所有代码路径以确定它们是否都返回是一项困难的操作,并且不需要实现来检查它.

  • 为什么代码在VC++中功能正常

这是体系结构和调用约定依赖.请尝试以下代码:

#include <iostream>

int fun (int v)
{
    int a = v;
}

int main ()
{
    std::cout << fun(5) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在不同的编译器上,函数fun返回0任何值或传递给它的任何值.基本上它可以返回上次计算表达式的值.