【问题标题】:recursive function error Dev-C++递归函数错误 Dev-C++
【发布时间】:2012-06-08 07:52:58
【问题描述】:

我有以下代码顺序搜索在 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++ 之间存在这种差异?

【问题讨论】:

  • 递归顺序搜索??
  • else seqSearch(list, index, item); 没有返回任何内容。将其更改为else return seqSearch(list, index, item);。
  • 很可能与您的问题无关,但您可能希望查看 Dev-C++ 以外的其他 IDE 以获取 reasons listed here。
  • Vikas 是对的,添加 else return seqSearch(list, index, item);我如何接受你的回答?
  • 顺便说一句,你不应该看到不同的行为。是不是搞错了?

标签: c++ algorithm visual-c++ recursion dev-c++


【解决方案1】:

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

现在挖得更深了。

来自n2960草稿:

§ 6.6.3/2

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

所以根据标准,这是一种未定义的行为。

再深入一点:

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

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

  • 为什么代码在 VC++ 中正常工作

这是架构和 calling convention 相关的。试试下面的代码:

#include <iostream>

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

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

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

【讨论】:

    【解决方案2】:

    正确的方法定义应该是

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

    您错过了退货声明。理想情况下,编译器应该会警告您,但我对 Dev-Cpp 使用的版本不太熟悉。

    【讨论】:

    • 仍然感谢您看到我的问题,在 VC++ 中无需添加“return”它仍然运行良好,这很奇怪吗?
    • 不,它是特定于实现的。为了符合标准,您应该有一个退货声明。否则,它可能会起作用,也可能不起作用,具体取决于您所使用的编译器。
    猜你喜欢
    • 2017-12-25
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多