首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归函数错误Dev-C++

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

Stack Overflow用户
提问于 2012-06-04 15:46:45
回答 2查看 1.8K关注 0票数 0

我让下面的代码顺序搜索在Visual C++中完美地运行

代码语言:javascript
复制
#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++之间会有这样的区别?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-06-04 16:34:30

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

现在深入挖掘一下。

n2960草稿:

§6.6.3/2

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

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

再深入一点:

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

检查所有代码路径以确定是否所有代码都返回是一项困难的操作,实现不需要检查这一点。

  • 为什么代码在VC++

中功能正常

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

代码语言:javascript
复制
#include <iostream>

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

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

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

票数 5
EN

Stack Overflow用户

发布于 2012-06-04 15:56:37

正确的方法定义应该是

代码语言:javascript
复制
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使用的版本。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10877955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档