| ▲ | augustk 5 hours ago | |||||||
It's also worth noting that statements like
are just as bad since `break' (and `continue' and early `return') are a just gotos in disguise. | ||||||||
| ▲ | matthewkayin 3 hours ago | parent | next [-] | |||||||
They are just gotos, but does that mean that they are bad (along with their friend try/catch, who is also a goto?), or does that mean that gotos can be useful when used with restraint? Gotos get a bad rep because they become spaghetti when misused. But there are lots of cases where using gotos (or break/continue/early return/catch) makes your code cleaner and simpler. Part of a programmer's job is to reason about code. By creating black and white rules like "avoid gotos", we attempt to outsource the thinking required of us out to some religious statement. We shouldn't do that. Gotos can be useful and can lead to good code. They can also be dangerous and lead to bad code. But no "rule of thumb" or "programming principle" will save you from bad code. | ||||||||
| ▲ | jcranmer 2 hours ago | parent | prev [-] | |||||||
Yes, break, continue, and return are all "just" gotos in disguise. But they restrict the power of the goto enough to not cause the problems that goto causes while providing a good deal of semantic power to users. Namely, all of these are essentially variations on early return (you can also throw in the logical && and || operators here, albeit they are slightly different in having two exit points rather than one--they're a fusion of if and break, essentially). And it sort of turns that there are a lot of cases where "return when any of these conditions, tested in a particular order, holds" turns out to be the most natural way to express an algorithm, and these goto-like constructs are the most natural way to write them. (FWIW, this is essentially the argument that Knuth makes in his defense of goto paper) | ||||||||
| ||||||||