Search code examples
recursionstack-overflowinfinite-loop

When will infinite loops, and recursive functions with no stop conditions, eventually stop?


I heard a myth saying that infinite loop or a recursive function with no stop condition will stop when "the stack overflows". Is it right?

For example :

void call()
{
call(); 
} 

or

for(;;){;}

Will they really stop when the stack overflows?

Update: If it really stops, can I detect after how many recursive calls?


Solution

  • It really depends on the choice of language.

    In some languages, your infinite recursive function will halt with a stack overflow based on system- or language-dependent conditions. The reason for this is that many implementations of function call and return allocate new space for each function call, and when space is exhausted the program will fail. However, other languages (Scheme and various gcc optimization levels) will actually have this program run forever because they are smart enough to realize that they can reuse the space for each call.

    In some languages, infinite loops will run forever. Your program will just keep on running and never make progress. In other languages, infinite loops are allowed to be optimized away by the compiler. As an example, the C++ standard says that the compiler is allowed to assume that any loop will either terminate or make some globally-visible action, and so if the compiler sees the infinite loop it might just optimize the loop out of existence, so the loop actually does terminate.

    In other words, it really depends. There are no hard-and-fast answers to this question.

    Hope this helps!