I have a design
while(true){ for(;;) {} } How do I get out of an infinite while loop inside a for loop?
Unfortunately, unlike Java, C and C ++ do not support a mechanism like a break label , so the most clean option is to use goto:
int main() { while (true) { for (;;) { goto breakAll; } } breakAll: puts("I'm out!"); } You can also use the flag:
int main() { bool running = true; // bool определен в stdbool.h while (running) { for (;;) { running = false; break; } } puts("I'm out!"); } There is no big difference between these options.
In addition to this case, goto also used in good C style for error handling:
bars_t foo() { bar_t *bar1 = malloc(sizeof(*bar1)); if (!bar1) { goto cleanupNothing; } bar_t *bar2 = malloc(sizeof(*bar2)); if (!bar2) { goto cleanupBar1; } // ... return (bars_t) { .one = bar1, .two = bar2 }; // в обратном порядке определения cleanupBar2: free(bar2); cleanupBar1: free(bar1); cleanupNothing: return (bars_t){0}; } In C ++, this is not necessary, since There is RAII, but still go out of the cycles through the goto .
free() bursts and NULL :-) - user6550I'll add a couple of ways.
The specified code is placed in a separate function. And now you can go through the usual return .
Method two - you just need to create a variable flag. And check it out. Somewhere so
bool go = true; while(go){ for(;;) { if (...) { go = false; break;} } But this is a bad way.
try { while (true) { for (;;) { throw 1; } } } catch (int) { //вышли из двух вечных циклов одновременно } { while(1) { for(;;) { if(...) goto AWAY; } } AWAY: ; } inline bool func(){ bool exit,only_break; for(;;){ if(exit){ return 1; } if(only_break){ break; } } return 0; } int main(){ while(1){ if(func()){ break; } } } Source: https://ru.stackoverflow.com/questions/429037/
All Articles
goto:) - user6550C++times in tags :) - Outtruderwhile, and insidefor?), If you are supposed to leave them once. And variables to check the conditions for continuing the cycle - the most normal way. - Outtruder