Java Reference
In-Depth Information
This nonlinear control flow turns out to be extremely hard to read and understand
if you have more than one or two
goto
statements. Because the lines denoting the
goto
statements weave back and forth in complex flowcharts, the resulting code
is named spaghetti code.
In 1968 the influential computer scientist Edsger Dijkstra wrote a famous note,
entitled ȒGoto Statements Considered Harmfulȓ [
1
], in which he argued for the use
of loops instead of unstructured jumps. Initially, many programmers who had been
using
goto
for years were mortally insulted and promptly dug out examples in
which the use of
goto
led to clearer or faster code. Some languages offer weaker
forms of
goto
that are less harmful, such as the
break
statement in Java,
discussed in Advanced Topic 6.4. Nowadays, most computer scientists accept
Dijkstra's argument and fight bigger battles than optimal loop design.
236
237
6.2 for Loops
One of the most common loop types has the form
i
= start;
while (i <=
end)
{
. . .
i++;
}
Because this loop is so common, there is a special form for it that emphasizes the
pattern:
for (i =
start; i <= end; i++)
{
. . .
}
You can also declare the loop counter variable inside the
for
loop header. That
convenient shorthand restricts the use of the variable to the body of the loop (as will
be discussed further in Advanced Topic 6.2).
for (int i =
start; i <= end; i++)
{
. . .