Is there such a thing as labeling or an unlabeled gap in C?

As in Java, where an operator breakcan be labeled or unlabeled, is there a statement in C that is equivalent to or reaches the same process?

+4
source share
2 answers

No, there are no tagged break statements, as in Java. However, you can use goto-statement to achieve a similar effect. Just declare a shortcut right after the loop that you really want to exit, and use gotowhere you would use 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;
}

Conclusion:

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

, Dijkstras goto -statements , , , if while. , , (= ).

+4

, c , goto, Java, , .

goto, , goto, , goto , .

- . , , . , , Java, , , goto c.

+2

Source: https://habr.com/ru/post/1684255/


All Articles