Re: goto... is it so bad?
daniel_t@earthlink.net (Daniel T.) wrote (abridged):
OK, let's pretend we run the code fragments in a debugger with a
break-point at the line immediately after the comment "rest of the
program". What was the last line executed? You have a list of variable
values and the stack pointer...
With the goto version, you *cannot* know unless you were methodically
stepping through the fragment.
I sort-of agree, but it leads me to ask the question: why do you care?
Part of the benefit of refactoring into a separate function with a return
statement is that the separate function becomes a conceptual unit, a
black-box, and we can ignore what goes on inside it. We only care about
its inputs and outputs.
If you need to know whether it did the early return or fell off the end of
the loop, then you stick a break-point on the return statement itself. The
return statement corresponds to a, b and foo() all being true, and it does
so statically.
For reference, I'm talking about code like this:
void proc( int &a, int &b ) {
while (a) {
while (b) {
if (foo())
return;
}
// more code
}
}
Once it is in a separate function we can rewrite it to use the boolean
flag instead of return, but of course as soon as the function returns the
stack unwinds and value of the flag is lost, so we're no better off.
With the goto-less version, you can simply look at the values of
the variables and know.
That for me is a problem. We've given the code extra mutable state,
variables whose values change over time, so it becomes harder to analyse
statically from just the source code. In debugger terms, I can no longer
put a break-point on the code in the outer loop and know it will only be
reached if foo() is false. I have to make it a conditional break-point
instead. It's a little bit harder; I have to dig a little bit deeper.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]