Re: C++ FAQ
I think all this discussion goes to show that there
is hardly unanimity that "goto" should never be used.
On Jun 30, 7:53 pm, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
Alan McKenney wrote:
On Jun 30, 1:11 am, Francis Glassborow
<francis.glassbo...@btinternet.com> wrote:
....
The downside of "break" is that it leaves you at the
end of the loop. Sometimes you want to do some
processing that's only done if you fall through the
end of the loop. For example:
[ code w/ a loop with an exit via "goto" ]
[ rearranged code that doesn't use "goto" ]
I agree, in most, perhaps all cases, it is
possible to avoid using goto. The question is
whether the code w/o goto is clearer than the
code with goto. IMHO, there are situations
where "goto" is cleaner. "Clearer" and "cleaner"
are in the eye of the beholder, though.
BTW, "break" and "return" are themselves a kind of "goto".
Well yes and no. They are constrained in ways that make it hard if not
impossible to create spaghetti code.
Trust me, it is not that hard to write
spaghetti code in any language. I have
spent the past few weeks trying to untangle
some spaghetti C++, and there's not a goto
in it.
Yes It can be used to get out of a nest of loops, but generally a nest
of loops is symptomatic ....
In some lines of work, nested loops are inevitable. E.g.,
numerical calculations.
Not true. Just use function calls. They will make your code more
readable and less prone to errors during maintenance
I flatly disagree.
I do not see how, for instance, the following code can
be made "more readable" by encapsulating pieces in
functions:
for ( int i = 0; i < a_rows; ++i ) {
for ( int j = 0; j < b_cols; ++j ) {
double temp = 0.0;
for ( int k = 0; k < a_cols; ++k ) {
temp += A[i][k]*B[k][j];
}
C[i][j] = temp;
}
}
Anyone who has done matrix operations would instantly
recognize that this supposed to be a matrix multiply,
which they would not (instantly) if you put each loop
inside a separate function. Indeed, a lot of _compilers_
would recognize this as a matrix multiply.
Indeed, it is by putting little bits of code
in functions, so that you have to flip back and
forth to follow the flow of control, that you
end up with spaghetti code in C. Not to mention
that it makes it much harder for the compiler
to rearrange the code to improve performance
(to the extent that that is possible in C.)
The potential for spaghetti code is even greater
in C++, because now you have inheritance, virtual
functions, overloads with default parameters, etc.,
so you not only have to find function "f()", you
have to figure out which f() is the one you are
actually using at any particular time you hit that
line of code.
Been there, done that, still looking for the T-shirt.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]