Home > Software engineering >  can the break statement terminate the while(true) loop ? or only the return statement can do it?
can the break statement terminate the while(true) loop ? or only the return statement can do it?

Time:01-04

bjarne stroustrup chapter 6 calculator.cpp. I have edited part of the program. Ss it possible for the "at plus" to loop back to the "hey" without executing the break statement?

When I tried to calculate:

3 3 3 3 ;

I am confused how did the "at plus" loop back to the "hey" at the case ' '. I added the "at plus" and "hey" to try to know the flow of the statement.

// deal with   and -
double expression()
{
    cout << "expression" << endl;
    double left = term();      // read and evaluate a Term
    cout << "welcome to expression()" << endl;
    Token t = ts.get();        // get the next token from token stream
    cout << "still at expression()" << endl;


    while (true) {
        switch (t.kind) {
        case ' ':
            cout << "hey" << endl;
            left  = term();    // evaluate Term and add
            t = ts.get();
            cout << "at plus" << endl;
            break;
        case '-':
            left -= term();    // evaluate Term and subtract
            t = ts.get();
            break;
        default:
            ts.putback(t);     // put t back into the token stream
            return left;       // finally: no more   or -: return the answer
        }
    }
}

CodePudding user response:

The break statement can be somewhat confusing, because it can be used in a couple of different ways. Basically, it operates on the innermost thing that it could apply to. So those break statements that are inside the switch statement end the processing of the current case. That's all. A break statement outside the switch statement would end the loop:

void f() {
    while (true) {
        std::cin >> x;
        switch(x) {
            case 1:
                do_someting();
                break; // inside switch, so exits **this case**
            case 2:
                do_someting();
                break; // inside switch, so exits **this case**
        }
        break; // outside switch, inside while, so exits while
    }
    std::cout << "done\n";
}

CodePudding user response:

You missing code so I made example, remember it's usually bad practice, the code in case should be easy and readable. all you need to do is wrap the code you want to be executed more then once inside for/while loop, keep in mind break outside of the loop.

#include <iostream>

using namespace std;

int main()
{
    int j = 1;
    int k = 1;
    while(k > 0){
        switch(j){
        case 1:
            for (int  i =0; i <= 2; i   ){
               cout << "hey " << endl;
               cout << "bye " << endl;
            }
            k--;
            break;
        case 2:
            //execute this code
            break;
           }
   }
}

output: hey bye hey bye hey bye

  •  Tags:  
  • Related