0

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

4

2 回答 2

5

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

现在挖得有点深。

来自n2960草案:

§ 6.6.3/2

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

So as per the standard it is an undefined behavior.

Digging a little deeper:

  • Why is not returning from a non-void function not a compiler error?

Checking all code path to figure out if all of them return is a difficult operation and implementations are not required to check that.

  • Why is the code functionally working properly in VC++

This is architecture and calling convention dependent. Try following code:

#include <iostream>

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

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

On different compilers the function fun returns either 0 or whatever value is passed to it. Basically it can return value of last evaluated expression.

于 2012-06-04T08:34:30.067 回答
3

正确的方法定义应该是

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 使用的版本不太熟悉。

于 2012-06-04T07:56:36.790 回答