Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected infinite loop

This code runs for infinity, why?

    function f(n){
        i=0;
        if (n==2){
            while(i<2){
                f(i);
                i++;
            }
        }
    }

if n!=2 the function should do nothing and if n equals 2 the function calls f(0) and f(1) so it should stop after that but you only get infinite loop when you run it.

any one could tell why?

edit: there is nothing outside the function.

and no need for better code.Just asking why.

like image 393
MIE Avatar asked Dec 16 '13 19:12

MIE


People also ask

What is a common cause of an accidental infinite loop?

Unintended Infinite Loops In fact, these are loops that went wrong. Although they might be loops where you just forgot to put the exit condition, the most common cause of unintended infinite loops are the loops where there's an exit condition, but it might never become true.

How do you get out of an infinite loop?

You can press Ctrl + C .

What is meant by an infinite loop?

An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.


2 Answers

You can fix it by changing

i=0;

to

var i=0;

Your i variable is global (or at least its scope is external to f, so it's shared by all calls of the function). When n is initially 2, you enter the loop and this loop always resets i to 0 just before the increment. The sequence you have is thus

i = 0 // start of f
// enters loop for the first time with f(0)
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
i <2 so loop again
i = 0 // start of f
i = 1 // i++
...
like image 77
Denys Séguret Avatar answered Nov 15 '22 07:11

Denys Séguret


i is global. Declare it with var instead to keep it local to each instance. Otherwise, it is constantly reset to 0, so your while loop never ends.

like image 20
Tom Pietrosanti Avatar answered Nov 15 '22 08:11

Tom Pietrosanti