cswitch-statementbreaklabeled-statements

Is there such a thing as labeled or unlabeled break in C?


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?


Solution

  • 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).