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 seqSearchhas a code path,else seqSearch(list, index, item);that is not returning anything. Changing this toelse return seqSearch(list, index, item);should solve the problem.Now digging a little deep.
From n2960 draft:
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:
On different compilers the function
funreturns either0or whatever value is passed to it. Basically it can return value of last evaluated expression.