4 ms·
>> - Using a single goto and single label to exit several levels of scope. > Better handled by putting the nested scope in a function and using `return`. I du
by OskarS 3y ago
>> - Using a single goto and single label to exit several levels of scope.
> Better handled by putting the nested scope in a function and using `return`.
I dunno, that seems pretty silly to me. It's a perfectly valid use case of goto to jump out of deeply nested loops, and refactoring it to break out the inner loop in a function seems like pointless busy-work that ultimately makes the code harder to read, just so you can avoid a goto.
- clauderoux 3y ago@OskarS I agree with you... In fact, I have been avoiding gotos as a matter of principle for years and now reading the different discussions, I think I was misled. This case is very, very common. You have 3 intertwined loops and you want to get out. The traditional solution is to add some intermediate variables to propagate the end of the loops, with a cascade "if (toto) break;" which are far from being exquisitely elegant... Using a function for that is really adding some more complexity and some more stuff on the stack for nothing.
- clauderoux 3y agoAlso as a matter of technology, using "if" to get out of loops is bad with modern processors and their internal predictive algos. My solution for a long time was to add the test within the "for" itself, but it is often confusing for users.
- OskarS 3y agoExactly. The only reason not to use goto here is because of a dogmatic opposition to ever using goto. In fact, this is a rare case where goto makes the flow of the program more clear rather than less clear, and alternate solutions are just worse.