Array of function pointers

Hi,

I have a list of integers. I have to loop through list and depending on the value of the integer I have to call a relevant function.

At first I was going to implement a case statement to decide which function to call, but i wasn't happy with this - it seems like there should be a better way.

Eventually i thought of having an array of function pointers. each integer value in the list will correspond to an index of the array. So when I loop through the list i will just get the function pointer from the array and call the function.

My question is: will cause less overhead than using a case statement?
Yes, and your code will probably be easier to read, depending on the amount functions.
Last edited on
Cool

thanks skillless
The answer is only **Maybe**.

If the cases are ordered sequentially, then the compiler can make a jump table, which would mean
that the switch-case implementation would be equal to an array-based implementation. But the
difference would be so trivial I wouldn't worry about it.

Nonetheless, IMHO I prefer data-driven design, so I would likely go with the array approach
provided that the array either can be constructed only once (ie, a static), or is small, and
provided that I can build the array in 1 line of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
int add( int a, int b ) { return a + b; }
int sub( int a, int b ) { return a - b; }
int mul( int a, int b ) { return a * b; }
int div( int a, int b ) { return a / b; }

int do_it( int a, int b, int op ) {
    typedef int (*fn)( int, int );

    static fn funcs[] = { add, sub, mul, div };
    
    assert( op < 4 && op >= 0 );
    return funcs[ op ]( a, b );
}



Topic archived. No new replies allowed.