I am just messing around with the function and somehow palindromes returns 74. I am using Visual studio 2022. Was it supposed to not return anything and catch compiler error since false is never returned in the case below?
bool palindromes(string str) {
if (str.length() == 0 || str.length() == 1) return true;
if (str[0] == str[str.length() - 1])
palindromes(str.substr(1, str.length() - 2));
else
return false;
}
int main()
{
cout << palindromes("lol");
}
CodePudding user response:
palindromes(str.substr(1, str.length() - 2));
is a typical mistake with recursion. I suppose you want to do something with the value returned from that call, but you ignore it. Recursive functions work very much the same as non-recursive functions, there is no implicit return
.
Very much related, the function does not return something when this condition str.length() == 0 || str.length() == 1
is false
but this condition str[0] == str[str.length() - 1]
is true
.
This line
palindromes(str.substr(1, str.length() - 2));
Does nothing. The function gets a parameter passed by value and the returned value is ignored.
Not returning something from a function that is declared to return something is undefined behavior.
Fix:
return palindromes(str.substr(1, str.length() - 2));
There might be other issues though.
CodePudding user response:
Seems that you ignored the warning:
warning C4715: 'palindromes': not all control paths return a value
This is a sin.
CodePudding user response:
Don't use recursion for what is a linear problem. Your multiple string copies add unnecessary overhead.
An alternative:
return std::equal(str.begin(), str.begin() str.size() / 2, str.rbegin());
This is readable and therefore less prone to bugs - your function not returning a value on all control paths is a bug: str.length() - 2
is vulnerable to unsigned
arithmetic.