Refactoring away labeled loops

After I was convinced that labeled breaks/continues are a total “nono” over here, I need help to remove the label out of my code.

I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.

I hope, the code-fragment is basically understandable…

for( int idx = 0; idx < vectorLength; idx++) {
    if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;

    for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
        if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
        if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
    setValueInVector( v, idx );

Please convince me, that there is a more readable/better version without the labels.


Looking at the solutions presented so far:

  • They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself

  • Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.

  • Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.

  • Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it’s executed.

All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn’t need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don’t think it should be treated as some unbreakable rule.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..