简体   繁体   中英

recursive function error Dev-C++

I have the following code sequential search run perfectly in 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; 
}

But in Dev-C++ it always display result 0, I tried to debug and see index is correct but why it display 0? Why we have this difference between VC++ and Dev-C++?

The function int seqSearch has a code path, else seqSearch(list, index, item); that is not returning anything. Changing this to else return seqSearch(list, index, item); should solve the problem.

Now digging a little deep.

From n2960 draft:

§ 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.

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.

The correct method definition should be

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);
} 

You missed out the return statement. Ideally a compiler should warn you but I'm not too familiar with the version that Dev-Cpp uses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM