Re: abusing exceptions
Jerry Coffin wrote:
In article <5q2dnVhM-Mxmv8DanZ2dnUVZ8qOknZ2d@bt.com>,
francis.glassborow@btinternet.com says...
[ ... ]
I am trying to understand the issue. If IIUC even on a system that does
not recognise that it can reuse the stack frame when executing tail
recursion, the largest recursion depth that does not exhaust the stack
is no slower than using setjmp/longjmp. So why would I want to use a
technique that does not unwind the stack when programming in C++?
The "technique that does not unwind the stack" seems to be a complete
red-herring.
Using real tail recursion (even if he could figure out how to do so)
would allow the code to run fast up to some number of iterations, but
would then die without a trace on at least some C++ implementations.
Using setjmp/longjmp or throwing an exception would be slower, but would
work for an arbitrary number of iterations.
So, your choices are:
1) tail recusion -- fastest, but most restricted
2) setjmp/longjmp -- slightly slower, but less restricted
3) exceptions -- generally slowest, but with the fewest restrictions.
There is obviously something that I am not getting here. Regardless as
to how you 'exit' the recursion you need a stack frame for each
(recursive) call of the function. Methods 2) and 3) both make it harder
for the compiler to analyze what the code is intended to do. That ion
turn makes it harder for a compiler to optimize its stack usage.
Why does this have a stack problem
int result;
void recur(int depth){
if (depth == 0) return ;
else{
result *= depth;
recur(depth - 1);
return;
}
}
void recurentry(int depth){
result = depth;
if (depth < 1) return;
else{
recur(depth - 1);
return;
}
}
that this one does not
int result;
void recur(int depth){
if (depth == 0) throw "stop" ;
else{
result *= depth;
recur(depth - 1);
}
}
void recurentry(int depth){
result = depth;
try {
if (depth < 1) return;
else{
recur(depth - 1);
}
}
catch(...){}
}
??
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]