This is for an assignment, its to check if a palindrome is true or not. If I run this in debug mode and follow through it does work, although the return values are something I have never seen before, they appear to be random numbers between 1-200 true or false, what am I doing wrong?
Your problem is that your function only returns a bool if one of the if statements are true. I debugged your program and they never become true, added a few lines for debugging purposes -
Yes I did my bad. When it executes the returntrue; it doesn't exit the function, it instead continues to print out hello on the screen, this smells like undefined behaviour to me, Im not 100% sure.
#include <iostream>
#include <string>
usingnamespace std;
bool isPalindrome(string, int, int);
int main()
{
string palindrome = "taco cat";
for (int i = 0; i < palindrome.length(); i++)
if (palindrome [i] == ' ')
palindrome.erase(i, 1);
int first = 0;
int last = palindrome.length() - 1;
bool test = (isPalindrome(palindrome, first, last));
cout << test;
}
bool isPalindrome(string palindrome, int forward, int backward)
{
if (palindrome[forward] != palindrome[backward])
return (false);
if (forward >= palindrome.length() - 1)
return (true);
//this line is incorrect
//isPalindrome(palindrome, ++forward, --backward);
//you need to return the value!
return(isPalindrome(palindrome, ++forward, --backward));
}