Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain the program flow in this C++ function

Tags:

c++

I wrote a strange function to find the factorial of a number

int strange_fact(int n=0)
{
    static int i=n;
    static int j=i;
    if(j>1)     
    {       
        i *= --j;
        strange_fact();         
        return 0x7777;    //<------ This line
    }
    else
        return i;
}

When I commented the 9th line, I was getting the expected output. But I encountered a strange (or maybe not so strange) behaviour after adding that line. What happens when I uncomment it is that program flow reaches line 9 even though a recursive function call precedes it. My question is, how does flow reach line 9?

like image 326
Shiva Avatar asked Aug 30 '26 19:08

Shiva


1 Answers

When recursive call to function ends, line 9 will be reached. See this (shorter) example:

int foo(int i) {
    if(i > 0) {
        foo(i-1);
        return 0x7777;
    } else {
      return i;
    }
 }

So when calling foo(1) it will go through first if (because 1 > 0) and foo(0) will be called. Now inside this call (foo(0)) program will go into else barnch (because 0 is not > 0) and foo(0) will return 0. So now we will be back to our first call (foo(1)) and as foo(0) returned, foo(1) will return 0x7777.

like image 65
zoska Avatar answered Sep 02 '26 10:09

zoska



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!