Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any language that allows a break through multiple loops?

break interrupts a for-loop in most languages, but in the case of nested loops I have never encountered an n-th order break.
1. Is there such a thing in any language?
2. If so what is the correct name for it?
3. If not, why?
NB. I am not looking for workarounds.

Regarding point 3. The closest thing I know is goto, which should not be used as it leads to spaghetti code (Python has it only in a joke module), but this seems like a different problem as a boolean variable to mark an inner break, catching a raised a custom error or moving the block to a function in order to break with return are a lot more convoluted (in terms of line numbers and variables in the code).

(This is a curiosity question from a theoretical point of view, but if it helps, I code primarily in Python, Matlab and JS. I have know Perl, Pascal and Basic, but I know only the basics of C++ and know shamefully little of machine code.)

like image 631
Matteo Ferla Avatar asked Dec 15 '25 20:12

Matteo Ferla


2 Answers

Java has a labeled break statement that lets you break out of any number of loops:

search:
    for (i = 0; i < arrayOfInts.length; i++) {
        for (j = 0; j < arrayOfInts[i].length;
             j++) {
            if (arrayOfInts[i][j] == searchfor) {
                foundIt = true;
                break search; // <<=== This statement breaks both nested loops
            }
        }
    }
like image 156
Sergey Kalinichenko Avatar answered Dec 17 '25 10:12

Sergey Kalinichenko


PHP allows for "multi-level breaks" (eg. break 3 which breaks you out of three levels of loops), these are discussed here:

https://www.php.net/manual/en/control-structures.break.php

Bash also has this functionality:

https://tldp.org/LDP/abs/html/loopcontrol.html

(The term "multi-level break" appears in a 2008 article in Mathematics of Program Construction, but I don't believe this is the first appearance of the terminology: https://dl.acm.org/doi/abs/10.1007/978-3-540-70594-9_11)

like image 33
Rand00 Avatar answered Dec 17 '25 10:12

Rand00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!