c++ - 递归函数错误Dev-C++

标签 c++ algorithm visual-c++ recursion dev-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; 
}

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

最佳答案

int seqSearch 函数有一个代码路径,else seqSearch(list, index, item); 不返回任何内容。将其更改为 else return seqSearch(list, index, item); 应该可以解决问题。

现在深入挖掘一下。

来自 n2960草稿:

§ 6.6.3/2

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

因此,根据标准,这是未定义的行为。

再深入一点:

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

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

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

这是架构和calling convention依赖。试试下面的代码:

#include <iostream>

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

int main ()
{
    std::cout << fun(5) << std::endl;
}

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

关于c++ - 递归函数错误Dev-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10877955/

相关文章:

c++ - 为什么默认模板参数不适用于 using 声明?

c++ - 根据 bool 标准转换每个参数包的值

c++ - 具有多线程支持的 RenderClass,将函数调用推送到 vector 以在另一个线程上调用

c++ - 使用 Visual C++ 将二维数组 int[n][m] 写入 HDF5 文件

c++ - 升级到 C++ 20 时对运算符 new[] 的调用不明确

c++解密来自游戏客户端的消息

image - 按照 'logos'纵横比打分

c - 快速计算数组中较小/相等/较大元素的方法

Python RegEx-刽子手算法

c++ - 带字符的全局变量