Sobes.tech
Junior — Middle

What distinguishes infinite recursion from an infinite loop in programming?

sobes.tech AI

Answer from AI

Infinite recursion and an infinite loop both lead to endless code execution, but they differ in mechanism and consequences:

  • Infinite loop — is a loop (for example, while(true)) that never terminates, but does not cause additional memory consumption on each iteration. It runs in the same call stack.

  • Infinite recursion — a function calls itself without an exit condition, causing each call to add a new frame to the call stack. Eventually, the stack overflows, and the program crashes with a stack overflow error.

Example of an infinite loop in Python:

while True:
    print("Infinite loop")

Example of infinite recursion in Python:

def recurse():
    recurse()

recurse()

Thus, an infinite loop usually just "hangs," while infinite recursion leads to a crash due to stack overflow.