Switch-Case and Nested Breaks?

Hi all,

Relatively simple question. When using a switch/case statement, can breaks which exit the switch be placed within their own if/else statements? For example, below if someCondition, otherCondition, or YetOtherCondition were true, would the break in either if statement exit the switch before defaulting to AnotherVar = 3? I'm under the impression that within a switch statement any break, no matter how deeply nested in if/else, can exit the switch. Is my impression correct? Just checking for potential gotchas here. Thanks!

(for the sake of simplicity I haven't included the default or any other cases)

switch (SomeVar) { case 0: if (someCondition) { AnotherVar = 1; break; }

if (otherCondition) { if (YetOtherCondition) { AnotherVar = 2; break; } }

AnotherVar = 3;

break; } //end of switch-case

You can have break inside an if statement, and it will exit the case, but if you have it inside a loop, it will only exit the loop.

switch (SomeVar) {
  case 0:
     while (someother condition) {
         if (thirdcondition)
             break;    /* goes to FOO */
         more code;
     }
FOO:
     if (someCondition) {
       AnotherVar = 1;
       break; /* goes to BAR */
     }
     more code
   } // end of switch
BAR:

Why do you need to do that? Just rearrange the logic.

switch (SomeVar) {
 case 0: 
    AnotherVar = 3;  // the default setting
    if (someCondition) {
      AnotherVar = 1;
    }
    else if (otherCondition) {
       if (YetOtherCondition) {
           AnotherVar = 2;
      }
    }
   break;
} //end of switch-case

@Henry_Best & all,

Thanks for the feedback. I didn't want to convolute the example but suffice it to say this code is doing motor control with force feedback and there are lots of corner cases that would be difficult to fully explain here. Had to do the due dilligence to make sure I was considering all potential ways to implement.

Dee_C: Hi all,

Relatively simple question. When using a switch/case statement, can breaks which exit the switch be placed within their own if/else statements? For example, below if someCondition, otherCondition, or YetOtherCondition were true, would the break in either if statement exit the switch before defaulting to AnotherVar = 3? I'm under the impression that within a switch statement any break, no matter how deeply nested in if/else, can exit the switch. Is my impression correct? Just checking for potential gotchas here. Thanks!

(for the sake of simplicity I haven't included the default or any other cases)

switch (SomeVar) { case 0: if (someCondition) { AnotherVar = 1; break; }

if (otherCondition) { if (YetOtherCondition) { AnotherVar = 2; break; } }

AnotherVar = 3;

break; } //end of switch-case

Surely you realize that code could more properly be written as a simple if-else if- else?

Regards, Ray L.