Dynamic jump to label in C

后端 未结 5 960
清酒与你
清酒与你 2021-01-05 01:29

I would like to display the output - numbers 1 to 5, followed by 4-5 infinitely. Is there any way i can pass the value of i(4) instead of the character i in goto1. Or is the

5条回答
  •  粉色の甜心
    2021-01-05 02:07

    Are you asking for a jump table? If you are using gcc: It has a jump table mechanism.

    #include 
    
    int main()
    {
        unsigned char data[] = { 1,2,3,4,5,4,5,0 };
        // data to "iterate" over, must be 0-terminated in this example
    
        void *jump_table[] = { &&L00, &&L01, &&L02, &&L03, &&L04, &&L05 };
        // you should fill this with all 256 possible values when using bytes as p-code
    
        unsigned char *p = data;
    
        begin:
            goto *jump_table[ *p ];
    
        L00:
            return 0; // end app
        L01:
            printf("num %i\n", (int)*p);
            goto next;
        L02:
            printf("num %i\n", (int)*p);
            goto next;
        L03:
            printf("num %i\n", (int)*p);
            goto next;
        L04:
            printf("num %i\n", (int)*p);
            goto next;
        L05:
            printf("num %i\n", (int)*p);
            goto next;
        L06:
        L07:
        // ...
        LFF:
            goto next;
    
        next:
            ++p;            // advance the data pointer to the next byte
            goto begin;     // start over
    
        return 0;
    }
    

    The pro about this method is that you spare the large switch statement.

提交回复
热议问题