Re: goto... is it so bad?
Francis Glassborow wrote:
It is also clear that the outer loop terminates when something is true.
Though I do try to avoid using break to exit a loop (unless it is the
only way out so I might actually write:
while(true){
while(b and not something){
// code which might change the
// truth value of something
}
if(something or not a) break;
// more code
}
Which also makes it clear that the outer loops termination condition is
actually that a be true and something be false.
Whether that is clearer or not is a personal matter of style and
opinion. To me, this example is less clear than the goto version. One
reason I use gotos is to avoid code duplication and duplicate testing of
conditionals (the "something" in your example). I find duplication to be
a maintenance problem because I have to a) visually check to ensure they
really are duplicates and b) remember that when I change one, I must
change the other in sync. Even worse, the need to move "something" out
of the inner loop may require declaring more variables and moving
declarations of variables out of inner scopes, and spreading the
initialization/use of such variables across larger swaths of code. For
example:
while(a) {
while(b) {
if(foo())
goto out_a; // exit the outer loop
}
// more code
}
out_a: // rest of the program
becomes:
while(true){
bool tmp = false;
while(b && !(tmp = (foo() != 0))){
// code which might change the
// truth value of something
}
if(tmp or not a) break;
// more code
}
I have to look at that pretty carefully to see if it really is the same
as the simple goto version.
And yes, you can keep coming up with counter examples, and I can keep
shooting them down. That is just tedious.
I think we can all agree that since it's been proven that one can always
be transformed into the other, it is pointless to produce counter
examples showing that it can be done.
Walter's upthread examples are exactly what I would expect from someone
who (like me) learnt his craft with assembler.
Basic, FORTRAN, and assembler, all of which relied on goto <g>.
The problem caused to
maintenance is that you have to check every change at both the come from
and arrive at point.
As opposed to checking the duplication of code (even if the optimizer
can get rid of the duplication, the maintenance programmer still has to
see it, check it, etc.)
I don't use goto gratuitously - if a structured statement will fit, I'll
use that instead. If it doesn't, I won't. I try not to use a crowbar as
a hammer, either, even if it can drive nails <g>. I might also add that
I use fewer goto's in D programming because D has a richer panopoly of
structured statements that obviate many uses of gotos, such as
multilevel breaks (useful in the above example) and scope guards.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]