Reputation: 1696
I accidentally wrote some code that contained lines that looked this today:
public void fun1(args){
fun2(args);
}
public void fun2(args){
fun1(args);
}
It was in Java and so when the code was run, it produced a stack overflow and the code crashed. No problem there.
But this is based on Java, and I've seen this in other languages as well (mostly OO or imperative languages). Are there any languages that support recursion for which this would not result in a stack overflow, but perhaps a different error type? Or would "allow" the infinite loop to run indefinitely, maybe with sufficient memory?
Upvotes: 1
Views: 110
Reputation: 1184
Infinite loop does not always result in a crash if it does not require additional memory for each iteration.
Infinite recursion does not always result in a crash, especially if it is a tail recursion and depending on the compiler/programming language.
"Scheme" supports tail recursion.
Upvotes: 0
Reputation: 21912
The reason it goes into memory is because the runtime keeps track of a context stack into which is stores the local variables. A new context is added to the stack every time you enter a method (technically in Java-like languages, every time it encounters a '{'
So, basically if you wanted this to work, you want no context tracking. Assembler seems like a very good candidate. But it comes with it's own problems.
Better yet, why would you ever want to so something like that... You might want to reevaluate what you are doing...
Upvotes: 0
Reputation: 994947
Yes, a language with tail call optimisation will avoid the stack overflow problem in this case. For example, the following Scheme code would execute indefinitely when one of the following functions is called:
(define (fun1 args)
(fun2 args))
(define (fun2 args)
(fun1 args))
Upvotes: 8