1

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;  
5
  • Please edit your code to show some reason to exit the while loop, preferably an if statement. Commented Dec 8, 2016 at 1:49
  • So to be clear, this is multithreaded or reentrant in some other way (e.g. through a signal handler, or one of the methods called in the case '5': loop)? Because otherwise, you'll never reach case '6': to terminate the loop. Commented Dec 8, 2016 at 1:55
  • I have edited the code Commented Dec 8, 2016 at 2:26
  • is this inside of the function? Commented Dec 8, 2016 at 2:27
  • Yes it runs in a while loop in the main function Commented Dec 8, 2016 at 2:38

3 Answers 3

1
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;  
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

case '5': 
  while(!stop)
  {

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

1 Comment

What you propose in your answer won't keep the loop from going on forever.
0

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~~
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.