samedi 9 janvier 2016

Why do recursive function in C interrupts in the middle?

Vote count: 0

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]!='\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++;
        }
    }
}

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

asked 2 mins ago

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.



Why do recursive function in C interrupts in the middle?

Aucun commentaire:

Enregistrer un commentaire