这个递归函数(回文)变成了一个无限循环

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

本文关键字:一个 无限循环 回文 递归函数      更新时间:2023-10-16

/*但如果我将第13行更改为"else return回文(s,++f,--l);",则代码运行良好。这是什么原因?*/

#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: %dn",len);
    int b = 0;
    if(palindrome(a, b , len))
    {
        printf("Plindromen");
    }
    else
    {
        printf("not palindromen");
    }
}

签名

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

并调用

f = first index, l = last index;`

错误

++f/--l在递归中没有任何作用,除非您将其作为引用参数传递:

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

让我猜猜看。是

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

这意味着对于递归调用回文f永远不会得到增量。它将在函数调用后递增。在你的情况下永远不会。