Search code examples
crecursionstaticpalindrome

static variable in recursive function in c


I'm writing a program that checks if a number is a palindrome using recursion. I used a static variable to keep the value of the number written backwards and at the end I compared if it was equal to the original number.

It works fine when testing one number but if I try to check more than one number (I ask the user to input a few numbers in a for loop in the main), it checks the first number just fine but the others it doesn't.

Is there a way to reset the static variable back to 0 after the recursion ends (after checking one number)?

bool IsPalindrome(unsigned int number) {
    static unsigned int Inverse = 0;
    unsigned int OriginalLastDigit, OriginalNumber=number;
    if (number != 0) {
        OriginalLastDigit = number % 10;
        Inverse = Inverse * 10 + OriginalLastDigit;
        IsPalindrome(number / 10);
    }
    if (OriginalNumber == Inverse) {
        return true;
    } else {
        return false;
    }
}

Solution

  • Structuring it as

    bool IsPalindrome(unsigned int number) {
      unsigned int Inverse = 0;
      return IsPalindromeHelper(number, &Inverse);
    }
    

    with your original code slightly changed so the signature is

    bool IsPalindromeHelper(unsigned int number, unsigned int* Inverse)
    

    Is probably the easiest way to accomplish what you want to do. Knowing when to reset a static variable isn't feasible, short of passing in a flag... but if you're passing in a flag it's much cleaner to just pass in the variable itself as others have noted.