I am trying to implement binary search tree and trying to implement searching the value from a node. The book implements it through recursion.
To understand the procedure better, I am trying to apply the logic on an array.
Consider below code:
#include <iostream>
#include "BST.h"
using namespace std;
char Array[]={'A','B','C','D','E','F','G','H','I','J'};
char fn(int i,int x)
{
if( i == x)
{
cout << "Case : 1 " << endl;
return Array[x];
}
else if( i > x)
{
cout << "Case : 2 " << endl;
fn(--i,x);
}
else if(i < x)
{
cout << "Case : 3 " << endl;
fn(++i,x);
}
}
int main()
{
cout << fn(2,7) << endl ;
system("Pause");
return 0;
}
What I am trying to achieve is fn(int i,int x): from index i , search index x and return the value at index x
.
The output is:
Case : 3
Case : 3
Case : 3
Case : 3
Case : 3
Case : 1
H
Press any key to continue . . .
The recursion logic works fine. But while compilation, it shows warning as main.cpp(28): warning C4715: 'fn' : not all control paths return a value
So if I modify my code as:
char fn(int i,int x)
{
if( i == x)
{
cout << "Case : 1 " << endl;
return Array[x];
}
else if( i > x)
{
cout << "Case : 2 " << endl;
return fn(--i,x);//added return here
}
else if(i < x)
{
cout << "Case : 3 " << endl;
return fn(++i,x);//added return here
}
}
There is no compilation warning and output is exactly the same. My question is what purpose does return in each 'else if test condition' serve, I am returning from my base condition i.e. return Array[x]; and this is what I wanted my function to return. Why to put return in all the test conditions?
EDIT
Just realized, second version of function still giving compilation warning main.cpp(30): warning C4715: 'fn' : not all control paths return a value
What should be done? How to resolve?