A criticism of the break and continue statements is that each is unstructured. Actually they statements can always be replaced by structured statements, although doing so can be awkward. Describe in general how you would remove any break statement from a loop in a program and replace it with some structured equivalent. [Hint: The break statement leaves a loop from within the body of the loop. Another way to leave is by failing the loop-continuation test. Consider using in the loop-continuation test a second test that indicates "early exit because of a 'break' condition."]

Dani AI

Generated

The hint in the original post points to the usual, safe refactoring: make the loop stop when an extra condition becomes false instead of issuing break from inside the body. already sketched that idea with a boolean flag, but note the example uses if(break) as a placeholder — break is a reserved word in C++ and cannot be used as an identifier. Use a clearly named flag such as earlyExit or stopLoop.

A simple structured transform (keeps the same local scope and avoids extra jumps):

bool earlyExit = false;
for (int i = 0; i < n && !earlyExit; ++i) {
    // work for this iteration
    if (some_condition) earlyExit = true;   // replaces 'break'
    // remaining work that should be skipped when earlyExit is set
}

An alternative that is often clearer is to extract the loop body into a function and use return for early exit. Returning is structured control flow and avoids introducing flags that must be checked in multiple places:

bool process_items(...) {
    for (...) {
        if (stop_condition) return true;   // structured early exit
        // work
    }
    return false;
}

Special cases and cautions: a break inside a switch behaves differently (it exits the switch, not an enclosing loop), so replacing such uses may require rewriting the switch as if/else or moving the control test out. For nested loops, propagating a flag to the outer loop works but can get awkward; extracting into a function and using return is usually cleaner. Exceptions are for exceptional errors, not normal loop control. For formal semantics of break, see the C++ reference on the break statement: break statement semantics.

Recommended Answers

All 2 Replies

Do your own homework

bool quit = false;
while(!quit) //And some other conditions, obviously
{
    //Do something
    if(break)
       quit = true; //Break out of the loop by failing the condition for the loop, without using break
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.