I have a design
while (true) {
for (;;) {}
}
How do I get out of the infinite WHILE cycle inside the FOR cycle?
Answer 1, Authority 100%
Unfortunately, unlike Java, C and C++ do not support the mechanism like BREAK LABEL
, so the cleanest 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 is defined in stdbool.h
While (Running) {
for (;) {
Running = False;
Break;
}
}
Puts ("I'm Out!");
}
Large difference between these options is not.
In addition to this case, Goto
is also used in a good C for error handling:
bars_t foo () {
BAR_T * BAR1 = Malloc (SizeOF (* Bar1));
If (! Bar1) {
Goto CleanUnothing;
}
BAR_T * BAR2 = Malloc (SizeOf (* Bar2));
If (! Bar2) {
Goto CleanupBar1;
}
// ...
Return (Bars_T) {
.one = bar1,
.two = BAR2.
};
// in the reverse order of definition
CleanupBar2:
FREE (BAR2);
CleanupBar1:
FREE (BAR1);
CleanUnothing:
RETURN (BARS_T) {0};
}
in C++ this is not necessary, because There is Raii, but from cycles still go through Goto
.
Answer 2, Authority 71%
I will add a couple of ways.
The specified code is submitted to a separate function. And now you can go on the usual Return
.
Method two – you need to create a variable flag. And check it. Somewhere so
bool go = true;
While (GO) {
for (;;) {if (...) {go = false; Break;}
}
But this is a bad way.
Answer 3
try
{
While (True)
{
for (;;) {throw 1; }
}
}
Catch (int)
{
// came out of two eternal cycles at the same time
}
Answer 4
{
While (1)
{
for (;;)
{
if (...)
Goto Away;
}
}
Away:;
}
Answer 5
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;
}
}
}