Search code examples
cfunctionpointersc89

Buffer of function pointers?


I know it may sound sci-fi but I truly want to call a function x times, by using an array of function pointers to it and without involving a loop or anything that may slow down the target program. Is that possible and if yes, how exactly?


Solution

  • Here's an example of depth limited recursion

    void hello( int depth )
    {
        printf( "hello %2d\n", depth );
        if ( depth > 1 )
            hello( depth - 1 );
    }
    
    int main()
    {
         hello( 10 );    // call the hello function 10 times
         hello( 17 );    // call the hello function 17 times
    }
    

    And here's an example of calling a function pointer multiple times using a jump table. Note that with the jump table, the maximum number of calls is limited to the size of the jump table (10 in this example) whereas with recursion, the number of calls is limited only by stack size.

    int hello( int n )
    {
        n++;
        printf( "hello %2d\n", n );
        return n;
    }
    
    void executeFunction( int (*func)(int), int count )
    {
        int n = 0;
        switch ( count )
        {
            case 10:  n = (*func)(n);
            case 9:   n = (*func)(n);
            case 8:   n = (*func)(n);
            case 7:   n = (*func)(n);
            case 6:   n = (*func)(n);
            case 5:   n = (*func)(n);
            case 4:   n = (*func)(n);
            case 3:   n = (*func)(n);
            case 2:   n = (*func)(n);
            case 1:   n = (*func)(n);
        }
    }
    
    int main()
    {
        executeFunction( hello, 3 );   // call the hello function 3 times
        executeFunction( hello, 9 );   // call the hello function 9 times
    }