Dynamic jump to label in C

后端 未结 5 937
清酒与你
清酒与你 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:00

    Since you want to do this the wrong (aka. creative) way, have you considered trampolining?

    #include 
    
    typedef void (*generic)(void);
    typedef generic (*continuation)(void);
    
    generic first(void);
    generic second(void);
    
    int main(void) {
        continuation fubar = first;
        for (;;) {
            fubar = (continuation) fubar();
        }
    }
    
    generic first(void) {
        printf(" num is 1 \n"
               " num is 2 \n"
               " num is 3 \n");
        return (generic) second;
    }
    
    generic second(void) {
        printf(" num is 4 \n"
               " num is 5 \n");
        return (generic) second;
    }
    

    Continuing on from the idea of using function pointers (see what I did there? Giggity!), you could use an array of function pointers:

    #include 
    
    typedef size_t (*function)(size_t);
    
    size_t first(size_t);
    size_t second(size_t);
    
    int main(void) {
        function function[] = { first, first, first, first, second };
        size_t index = 0;
    
        for (;;) {
            index = function[index](index);
        }
    }
    
    size_t first(size_t index) {
        printf(" num is %d \n", ++index);
        return index;
    }
    
    size_t second(size_t index) {
        printf(" num is %d \n", index+1);
        return index-1;
    }
    

提交回复
热议问题