Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

recursion - Why do recursive function in C returns control to main, not previous call?

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.

Call:

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

void str_to_spol(char * str, char * spol)
{
    static int pos = 0;
    while(str[pos]!='')
    {
        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++;
        }
    }
}

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?

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

And the output is: 2 + 3

I'm using gcc 4.8.2

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]!='')
    {
        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("
");
    return 0;
}

Program output:

2 + 3 * 5 + 6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...