The answer by hivert identified your problem but in case you are at all concerned with performance consider using iterators or indices rather than making many string copies. Perhaps something like:
#include <iostream>
template <typename T>
bool palindrome(T begin, T end){
if (end - begin <= 1 )
return true;
--end;
if (*begin != *end)
return false;
++begin;
return palindrome(begin, end);
}
int main() {
std::string word(10000,'a');
if (palindrome(word.cbegin(), word.cend()) == true)
std::cout << "word is a palindrome" << std::endl;
else
std::cout << "word is not a palindrome" << std::endl;
}
But if you want to check a very long string you could get a stack overflow. If you are lucky the compiler might perform tail call optimization. Of course in this case it is easy to remove the recursion and use a loop instead:
#include <iostream>
template <typename T>
bool palindrome(T begin, T end){
while(end - begin > 1) {
--end;
if (*begin != *end)
return false;
++begin;
}
return true;
}
int main() {
std::string word(1000000000,'a');
if (palindrome(word.cbegin(), word.cend()) == true)
std::cout << "word is a palindrome" << std::endl;
else
std::cout << "word is not a palindrome" << std::endl;
}