I started learning C++ not long ago, and am trying to write a recursive function that determines whether or not an integer number is a palindrome (i.e. 12421 should return true, while 123 should return false). I can do this iteratively with little problem, but the given task is to use recursion, and with a function that only takes a single input-- here named test. Alas, for this I am not allowed to modify the function to accept more inputs, or else it'd surely be easier.
This is the code I have so far, and I can't figure out why it isn't working. The method I am attempting here is to take the integer, find the length of it and the first and last digits, and then recursively put the test value back into the function with the first and last digits "removed" so as to keep comparing until I reach the base case (test==0). The temp variables are... rather awkward but I don't how else to use the value of the original input without modifying it.
When I run it in Visual Studio, it gives a message on the second line saying "Exception thrown at 0x002D0C99 in ispalindrome.exe: 0xC0000005: Access violation writing location 0x00600F3C." Why would this be the case? Any help would be greatly appreciated.
bool is_palindrome(int test)
{
int length = 1, firstDigit, lastDigit;
int temp = test;
int temp2 = test;
int temp3 = test;
while (temp > 0)
{
temp /= 10;
length++;
}
while (temp2 >= 10)
{
temp2 /= 10;
}
firstDigit = temp2;
lastDigit = temp3 % 10;
if (test==0)
return firstDigit == lastDigit;
else
{
is_palindrome(test-(firstDigit*length)-lastDigit);
}
}