# Thread: Can someone explain why this simple recursion function crashes.

1. ## Can someone explain why this simple recursion function crashes.

Code:
```# include <stdio.h>

// if num = 5 print 4*2=8
// if num = 6 print 6*4*2 = 48

int even_prod(int num)
{
if (num%2 != 0)

return (even_prod(num-1));
else
return (num *(even_prod(num-2)));
}

int main()
{
printf("%d\n", even_prod(5));

return 0;
}```
it crashes but it should print 8 to the screen. Its under my nose but I don't know why.

2. Try using a debugger or adding some useful debugging output to see what's going on:
Code:
```int even_prod(int num)
{
printf("num = %d\n", num);
if (num%2 != 0)
return (even_prod(num-1));
else
return (num *(even_prod(num-2)));
}```
That should give you a huge clue.

3. You never return to main. In all cases you call the function recursively and eventually you run out of stack space.

A recursive function has a general form of
Code:
```foo( )
{
if( base-case )
return something/nothing
else
recursive-call
}```

4. Indeed, it is recursive on all control paths. I've actually seen a compiler warning about that once.

Code:
```int even_prod(int num)

{
if(num!=0)
{
if (num%2 != 0)
return (even_prod(num-1));
else
return (num *(even_prod(num-2)));
}
}

int main()
{
printf("%d\n", even_prod(5));

return 0;
}```

6. Originally Posted by eramit2010
Close, but not quite:
Code:
```\$ cat prod.c
#include <stdio.h>
int even_prod(int num)
{
if(num!=0)
{
if (num%2 != 0)
return (even_prod(num-1));
else
return (num *(even_prod(num-2)));
}
}

int main()
{
printf("%d\n", even_prod(5));

return 0;
}

\$ make prod
gcc -Wall -Wunreachable-code -ggdb3 -std=c99 -pedantic  -lm -lpthread  prod.c   -o prod
prod.c: In function ‘even_prod’:
prod.c:11: warning: control reaches end of non-void function```
You need to return something in the case that num is zero. Since it's a product function, the multiplicative identity (1) is a good choice.