Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use goto in a switch statement in Objective-C?

In my code I need to be able to jump (goto) a different case within the same switch statement. Is there a way to do this?

My code is something like this: (There is a lot of code I just left it all out)

switch (viewNumber) {
case 500:
        // [...]
break;

case 501:
        // [...]
break;
.
.
.
.
.

case 510:
        // [...]
break;

default:
break;

}

Thank you for your time! -Jeff

like image 952
Jeff Avatar asked Nov 19 '09 15:11

Jeff


2 Answers

It's generally very bad practice to unconditionally jump like you're asking.

I think a more readable/maintainable solution would be to place the shared code in a method and have multiple cases call the method.

If you really want to, you can use goto to do something like:

switch(viewNumber) {
    case 500:
        // [...]
        goto jumpLabel;
    case 501:
        // [...]
        break;
    case 502:
        // [...]
        jumpLabel:
        // Code that 500 also will execute
        break;
    default:break;
}

Note: I only provided the code example above to answer your question. I now feel so dirty I might have to buy some Bad Code Offsets.

like image 100
Ben S Avatar answered Oct 23 '22 05:10

Ben S


Instead of using goto, refactor your code so that the two (or more) cases that use common code instead call it in a common method.

Something like:

switch (value) {
   case (firstValue):
       // ...
       break;
   case (secondValue):
       [self doSharedCodeForSecondAndThirdValues];
       break;
   case (thirdValue):
       [self doSharedCodeForSecondAndThirdValues];
       break;
   default:
       break;
}

// ...

- (void) doSharedCodeForSecondAndThirdValues {
   // do stuff here that is common to second and third value cases
}

It wouldn't be the end of the world to use goto, though it is bad practice.

The practical reason for avoiding use of goto is that you have to search through your swtich-case tree to find that goto label.

If your switch logic changes, you'll have a messy situation on your hands.

If you pull out common code to its own method, the code is easier to read, debug and extend.

like image 34
Alex Reynolds Avatar answered Oct 23 '22 03:10

Alex Reynolds