I ran this program and it output
...
65088
65089
65090
and then it stopped. Windows 7 said a.exe stopped working. Here is the code:
#include <stdio.h>
void go(void);
main()
{
go();
}
void go(void)
{
static int i = 0;
printf("%d\n", i++);
go();
}
I think this program should keep on printing numbers indefinitely due to recursion, but it stops at 65090! The C code is compiled with gcc. Any ideas?
There is no theoretical limit to recursion depth in C. The only limits are those of your implementation, generally limited stack space. (Note that the C standard doesn't actually require a stack-based implementation.
Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.
Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely.
Different types of the recursionTail Recursion. No Tail/ Head Recursion. Linear recursion.
You are going to overflow the stack at some point because each call to go()
must push a return address on the stack even though you pass no arguments to the function call. So every call to go()
is taking up a pointer-sized block on the stack for that return address. Since the stack has a limited size, that means at some point you're going to run out of space. The C-language does not specify that a tail-call optimization should take place for circumstances like this, although some compilers (like gcc) do offer that option via optimization switches. But that would be something that is compiler-specific, and independent of the language specification.
It stops because it is overflowing the stack. Once you overflow the stack the results are undefined.
You cannot recurse infinitely on a machine with finite resources -- specifically, the stack. Each nested subroutine call required more stack space, and eventually you will run out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With