C中的递归函数:返回总是必要的吗?

nof*_*ofe 3 c

这是我第一次使用递归函数,我写的这个函数返回一个字符串的大小,如果它只包含升序的字母,如果不包含它返回-1.

在我拿出第二个"返回"之后,我不明白为什么它适用于这两个代码.比另一个更浪费一个吗?会欣赏一些见解.

with" return only_ascending_letters(string,index + 1);"

 #include <stdio.h>

    int only_ascending_letters(char string[], int index);

    void main() {
        char string1[]="Hi my name is pete";
        char string2[]="aabcdefg";

        printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));

    }

    int only_ascending_letters(char string[], int index){
        if(!string[index]) return index;
        if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1])) 
            return only_ascending_letters(string, index+1);
        else return -1;

    }
Run Code Online (Sandbox Code Playgroud)

with"only_ascending_letters(string,index + 1);"

 #include <stdio.h>

    int only_ascending_letters(char string[], int index);

    void main() {
        char string1[]="Hi my name is pete";
        char string2[]="aabcdefg";

        printf("the first string is %d and the second one is %d\n",only_ascending_letters(string1,0),only_ascending_letters(string2,0));

    }

    int only_ascending_letters(char string[], int index){
        if(!string[index]) return index;
        if(((string[index]>='a'&&string[index]<='z')||(string[index]>='A'&&string[index]<='Z'))&&((string[index]<=string[index+1])||!string[index+1])) 
        /*Took out the return*/ only_ascending_letters(string, index+1);
        else return -1;

    }
Run Code Online (Sandbox Code Playgroud)

jpa*_*cek 7

是的,你绝对需要回报.请注意,C语言规则对此问题有点松懈,如果您没有使用返回值,没有它就没关系.但是,您使用返回值,因此您需要return语句.

您所看到的可能是由于某些体系结构上的函数返回(整数值)的实现细节,通过将一个众所周知的寄存器设置为该值(i386上的eax).因此,如果最底层的递归调用执行return并设置此寄存器,并且中间的调用不会踩踏该寄存器,您会发现它有效.但是,你不能依赖它.

请注意,好的编译器会认识到这是一个尾递归调用,并且基本上以相同的方式编译两个变量.