Mithun Biswas
Mithun Biswas

Reputation: 43

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");
    }
}

Upvotes: 0

Views: 105

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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

Upvotes: 3

Oncaphillis
Oncaphillis

Reputation: 1908

Let me guess. It was

palindrome(s, f++, --l)

that means for the recursive call of palindrome f never gets increment. It would be incremented after the function call. In your case never.

Upvotes: 0

Related Questions