Search code examples
c++recursioninfinite-looppalindrome

this recursive function(palindrome) become a infinite loop.why?


/* but if I change the 13th line to "else return palindrome(s, ++f, --l);" then the codes run well. what is the reason for that?*/

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int palindrome(char* s, int f, int l)        // f = first index, l = last index; 
{
    if(f>=l) return 1;
    else if(s[f]!=s[l]) return 0;
    else return palindrome(s, f++,l--);
}

int main()
{
    char a[100];

    gets(a);
    int len = strlen(a)-1;
    printf("len: %d\n",len);
    int b = 0;

    if(palindrome(a, b , len))
    {
        printf("Plindrome\n");
    }
    else
    {
        printf("not palindrome\n");
    }
}

Solution

  • The signature

    int palindrome(char* s, int f, int l)    
    

    and calling on

    f = first index, l = last index;`
    

    is wrong

    ++f/ --l has no effect in the recursion, unless you're going to pass it as a reference parameter:

     int palindrome(char* s, int& f, int& l)
                             // ^       ^ Add a reference, if you're intending to change 
                             // the parameter value