Reputation: 13824
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++?
Upvotes: 0
Views: 1892
Reputation: 8948
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:
Checking all code path to figure out if all of them return is a difficult operation and implementations are not required to check that.
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.
Upvotes: 5
Reputation: 9415
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.
Upvotes: 3