I just wrote a function in C++ of checking whether a string is a palindrome.
bool isPal(string str, int s, int e) //s= starting index and e= (size of string -1)
{
if(s==e || s>e)
return true;
if(str[s]!=str[e])
return false;
return isPal(str, ++s, --e); //using return
}
Calling Statement:
cout<<isPal("aua",0,2);
Output: 1
On removing the return statement at the end, the function is producing a rather unexpected and arbitrary (which I'm not sure of) output.
Calling Statement:
cout<<isPal("aua", 0 , 2);
Output: 144
Without the return statement at the end, the code looks like this:
bool isPal(string str, int s, int e) //s= starting index and e= (size of string -1)
{
if(s==e || s>e)
return true;
if(str[s]!=str[e])
return false;
isPal(str, ++s, --e); //without return
}
What is the reason behind this output?
And what difference does it make if I'm not using the return
statement at the end of the recursion?
Ps: Coding environment Codeblocks.