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.
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.
You can press Ctrl + C .
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.
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++
...
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.
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