Is it possible to store the address of a label in a variable and use goto to jump to it?

前端 未结 14 1601
执念已碎
执念已碎 2020-12-04 09:35

I know everyone hates gotos. In my code, for reasons I have considered and am comfortable with, they provide an effective solution (ie I\'m not looking for \"don\'t do that\

相关标签:
14条回答
  • 2020-12-04 10:34

    The switch ... case statement is essentially a computed goto. A good example of how it works is the bizarre hack known as Duff's Device:

    send(to, from, count)
    register short *to, *from;
    register count;
    {
        register n=(count+7)/8;
        switch(count%8){
        case 0: do{ *to = *from++;
        case 7:     *to = *from++;
        case 6:     *to = *from++;
        case 5:     *to = *from++;
        case 4:     *to = *from++;
        case 3:     *to = *from++;
        case 2:     *to = *from++;
        case 1:     *to = *from++;
            }while(--n>0);
        }
    }
    

    You can't do a goto from an arbitrary location using this technique, but you can wrap your entire function in a switch statement based on a variable, then set that variable indicating where you want to go, and goto that switch statement.

    int main () {
      int label = 0;
      dispatch: switch (label) {
      case 0:
        label = some_computation();
        goto dispatch;
      case 1:
        label = another_computation();
        goto dispatch;
      case 2:
        return 0;
      }
    }
    

    Of course, if you do this a lot, you'd want to write some macros to wrap it.

    This technique, along with some convenience macros, can even be used to implement coroutines in C.

    0 讨论(0)
  • 2020-12-04 10:34

    You can do something like Fortran's computer goto with pointers to functions.

    // global variables up here
    
    void c1(){ // chunk of code
    
    }
    
    void c2(){ // chunk of code
    
    }
    
    void c3(){
    // chunk of code
    
    }
    
    void (*goTo[3])(void) = {c1, c2, c3};
    
    // then
    int x = 0;
    
    goTo[x++] ();
    
    goTo[x++] ();
    
    goTo[x++] ();
    
    0 讨论(0)
提交回复
热议问题