Marvinatorrr
Marvinatorrr

Reputation: 123

How to exit out of a while loop using switch case c++

How do I exit out of case '5' when I activate case '6'? I just cant seem to exit out of the loop. I have tried putting a break; inside of case '6' but that didnt seem to work.

case '5': //receive a '5' from serial com port and execute auto docking
 while(1)
{
 north =0;
 south=0;
 east=0;
 west=0;
 scanmovement();
 for(index=0;index<7;index++)
  {
    getdirection(index);
  }  
  arlomove();
  obstacleavoidance();

 }
  break;
 case '6':   //receive '6' from serial com port and stop auto docking
 //somethingsomething
 //break out of while loop in case '5' when this is activated
 break;  

Upvotes: 1

Views: 1448

Answers (3)

Sean83
Sean83

Reputation: 493

if it is in the function you can simply return when you reach 5.

For example,

void function(int n) {
    while(1) {
        switch(n) {
            case 5:
                blahblah~~
                return;
        }
    }
}

Or Simply you can use goto if it is the best option,

void main() {
    int n = 5;
    while(1) {
        switch(n) {
            case 5:
                blahblah~~
                goto theEnd;
        }
    }

    theEnd:
        blahblah~~
}

Upvotes: 0

tmaj
tmaj

Reputation: 35075

You cannot just stop case '5' but you could do something like this.

case '5': 
  while(!stop)
  {

  } 
  break;
case '6':
  //somethingsomething
  stop = true;
  break;

Upvotes: 1

dante
dante

Reputation: 1254

switch(var) // your variable
{
case '5': 
 while(1)
{
 north =0;
 south=0;
 east=0;
 west=0;
 scanmovement();
 for(index=0;index<7;index++)
  {
    getdirection(index);
  }  
  arlomove();
  obstacleavoidance();

 // var=....  update your var here     
 if(var=='6') { // do case 6 stuff
             break; // break out while when var = 6
             }
 }
  break;
 case '6':
 //somethingsomething
 //break out of while loop in case '5' when this is activated
 break;  
}

Upvotes: 1

Related Questions