为什么 C 中的递归函数将控制权返回给 main,而不是之前的调用?

问题描述:

我正在编写从经典表达式符号到逆波兰符号的转换器.当前的一段代码是错误的(有效,但与转换不同),但是当我调试它时,我发现了奇怪的返回行为.

I'm writing converter from classic expression notation to Reverse Polish notation. Current piece of code is wrong (works, but does something different than converting), but when I was debugging it I have discovered strange behavior of return.

调用:

str_to_spol( "(2+3)*(5+6)", a);

str_to_spol( "(2+3)*(5+6)", a);

void str_to_spol(char * str, char * spol)
{
    static int pos = 0;
    while(str[pos]!='\0')
    {
        if (str[pos]=='(') 
        {
            pos++;
            return str_to_spol(str,spol);
            pos++;
        }
        else if(str[pos]==')')
            return;
        else
        {
            spol[pos]=str[pos];
            printf("%c ", str[pos]);
            pos++;
        }
    }
}

在第一个符号'('函数调用自身,我们有两个函数.第二个函数工作直到遇到')',然后返回控制到最后函数,不在 if 里面!为什么会这样?

On the fisrt symbol '(' function calls itself, we have two functions. Second function works until it meets ')', then it returns control to the end of function, not inside if! Why is it so?

换句话说,输出应该是:2 + 3 * 5 - 6

In other words output should be: 2 + 3 * 5 - 6

输出是:2 + 3

我使用的是 gcc 4.8.2

I'm using gcc 4.8.2

您将第二个 pos++ 放在错误的位置.它应该在 next return 之前.发生的事情是,在返回检测到 ')' 时,每个调用者都检测到相同的 ')',并且调用堆栈下降到底部.

You have the second pos++ in the wrong place. It should be before the next return. What's happening is that on return having detected ')', the same ')' is detected by every caller, and the call stack drops to the bottom.

还有一个语法错误:函数不能返回值.

There is also a syntax error: the function cannot return a value.

#include <stdio.h>

void str_to_spol(char * str, char * spol)
{
    static int pos = 0; 
    while(str[pos]!='\0')
    {
        if (str[pos]=='(') 
        {
            pos++;
            str_to_spol(str,spol);    // <<--- removed `return`
        }
        else if(str[pos]==')')
        {
            pos++;                    // <<--- moved down
            return; 
        }
        else
        {
            spol[pos]=str[pos];
            printf("%c ", str[pos]);
            pos++;
        }
    }
}

int main(void){
    char str[] = "(2+3)*(5+6)";
    char spo[50];
    str_to_spol(str, spo);
    printf("\n");
    return 0;
}

程序输出:

2 + 3 * 5 + 6