The WTF in the code was the zilion lines, not the use of break
. The things that a lot of (mainly young) people fails to understand is that is not goto
in itself which is bad, but the spaghetti code using unwisely produces.
With goto
you can jump everywhere in the code (well, almost everywhere, you can not jump from outside to inside a block). If you do not restrain yourself, the code becomes so tangled none can understand it anymore. On the other side, break
brings you just outside the current block, and looking for a closed brace brings you there.
As someone has remarked, this is mainly useful when you have exceptional (as in Exception) conditions where you should stop processing. Sure, you could do with if
s, like this
do {
// phase1
if (! something wrong) {
//phase2
}
}
But what if in phase 2 above there may be another exceptional condition? and another one.... you get something like
do {
// phase1
if (! something wrong) {
//phase2
if (! something else wrong) {
//phase 3
if (! something else again is wrong) {
//phase 4
}
}
}
}
Well, now compare it with the one you get with break
:
do {
// phase1
if (something wrong) break
//phase2
if (something else wrong) break
//phase 3
if (something else again is wrong) break
//phase 4
}
Where is the WTF? This use of break
is not a disguised goto but simply a poor man exception mechanism. The code above is fairly standard in Perl.
By the way, the linux kernel make a eavy use of goto
for error handling more or less in the way break
is used in the above example. This allows better streamlining of the code by the CPU and, incidently avoid code falling out from the right margin, seing as Linus insists on 8 spaces tabs and 80 coulms lines.