9

As is the case in Java where the break statement can be labeled or unlabeled, is there a statement in C which is either the equivalent or achieves the same process?

Antony Nepgen
  • 107
  • 2
  • 8
  • 4
    But there is `goto`, which Java doesn't have. – rustyx Aug 22 '17 at 19:54
  • you can think of the `break` statement as unlabeled break and `goto` as an extended labeled brake. – Serge Aug 22 '17 at 20:19
  • 1
    @Antony Nepgen The labeled break statement in Java is a demonstration of a bad style of programming by the authors of the language and nothing more. – Vlad from Moscow Aug 22 '17 at 20:29
  • The best way to do such things in C and Java both, is to wrap the whole switch inside a function and use a `return`. That's the "least spaghetti" way. – Lundin Aug 23 '17 at 13:54

1 Answers1

11

No, there are no labeled break-statements like in Java. You can, however, use the goto-statement to achieve a similar effect. Just declare a label right after the loop you actually want to exit, and use a goto where you would have used a labeled break in Java:

int main() {

    for (int i=0; i<100; i++) {
        switch(i) {
            case 0: printf("just started\n"); break;
            case 10: printf("reached 10\n"); break;
            case 20: printf("reached 20; exiting loop.\n"); goto afterForLoop;
            case 30: printf("Will never be reached."); break;
        }
    }
afterForLoop:

    printf("first statement after for-loop.");

    return 0;
}

Output:

just started
reached 10
reached 20; exiting loop.
first statement after for-loop.

Note that since Dijkstras famous paper Go To Statement Considered Harmful computer scientists have fought hard for banning goto-statements from code, because this statement often introduces much more complexity than control structures like if or while. So be aware what you do and use it wisely (= rarely).

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • 5
    Funny how this example of goto is actually much clearer than Java-spaghetti programming with labelled break/continue. They refused to implement goto in the language, then come up with something else ten times worse than goto... – Lundin Aug 23 '17 at 13:57
  • @Lundin You have a similar phenomenon with Golang's defer keyword. A `goto cleanup` is more intuitive, but not supported by the language. – matvore Apr 26 '21 at 21:28
  • 2
    @Lundin I disagree with this being clearer. I would find `break LOOP_NAME;` equally clear, but perhaps a slight bit easier to read, because I would read the loop name when reading the loop header and associate the label with the loop itself onward. – Kröw Mar 21 '23 at 18:15