Reputation: 2918
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?
Upvotes: 2
Views: 248
Reputation: 2918
Let us consider the case of strange_fact(3)
So, whatever happens in the recursive steps becomes meaningless because ultimately, 0x7777
will be return
ed when the control comes back to the first call.
Upvotes: 1
Reputation: 14074
You need to understand how recursions work.
After calling strange_fact()
you've put a return statement. Meaning once the function is executed, it's still going to return 0x7777
, which screws the answer up.
Check this out, this should work as expected:
int strange_fact(int n=0)
{
static int i=n;
static int j=i;
if(j>1)
{
i *= --j;
strange_fact();
// return 0x7777; // We don't want to return a value yet
}
if(j<=1) // We need to check this condition after strange_fact is executed
return i;
// This line will never be executed
return 0x7777; //<------ This line
}
If you eliminate the static variables, you'll get something like this:
long fact(long i)
{
if(i > 0)
return i * fact(i-1);
if(i == 0) // factorial(0) = 1
return 1;
throw exception("Negative numbers cannot have factorials"); // Or you can handle it by returning a -ve error code
}
Upvotes: 1
Reputation: 60037
This line
strange_fact();
does the recursion and throws away the result.
The next next line
return 0x7777;
will return that value finally.
If you remove that line and compiled with the warnings on it will inform you that all paths do not return a value
Upvotes: 2
Reputation: 1734
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.
Upvotes: 6