Reputation: 601
I need your help in writing a efficient program.
I have approx 50 functions say call_1()
, call_2()
... call_50()
. I need to call them based on the index read from a data packet, i.e if the field in data is 25 in need to call call_25()
, if 10 then call_10()
.
I have written this in if else condition like
if (index == 5)
call_5()
elseif (index == 6)
..so on ..
But I think this is not the efficient way of writing. Any other ideas of implementing this scenario? Can function pointers help here? Appreciate your help. thanks.
Upvotes: 0
Views: 121
Reputation: 782
Yeah, that is pretty inefficient. I think the best way to proceed is to write a dispatcher of this form in the range of 0 - 255:
void (*dispatcher[255]);
Of course, you would need to assign all the necessary functions instead of doing the if statements, but this would be a heck of a lot faster:
dispatcher['a'] = &call_1;
dispatcher['b'] = &call_2;
dispatcher['c'] = &call_3;
...
Then you can just do:
dispatcher(index) and it would know which function to execute.
Hope that helps.
Upvotes: 0
Reputation: 6389
I'd use a switch statement:
switch(index) {
case 1: return call01();
case 2: return call02();
case 3: return call03();
}
This is not a lot more code than using function pointers, and it's (imho) more concise.
Upvotes: 0
Reputation: 39807
Yes, function pointers are the way to go here.
I would suggest creating a table of function pointers and since your input is an index, you just index into the table to call the right function.
Upvotes: 0
Reputation: 476950
Yes, use a lookup table of function pointers:
typedef void(*fp)(void);
void call_01(void);
void call_02(void);
/* ... */
fp functions[] = { &call_01,
&call_02,
/* ... */
};
void call()
{
unsigned int n = get_index();
functions[n]();
}
Upvotes: 6
Reputation: 10541
You can use an array of function pointers there easily, if all your functions have the same signature.
typedef void (*func)(void);
...
func dispatch_table[] = {
func0,
func1,
func2,
...
func50,
};
And later use like this
int function_index = packet_get_func_index( packet );
...
dispatch_table[ function_index ]();
Upvotes: 1
Reputation: 399743
If the arguments are same for all 50 functions, use an array of function pointers:
typedef void (*FieldHandler)(void);
const FieldHandler handlers[50] = { call_0, call_1, /* ... and so on ... */ };
Then you just index into the array and call:
handlers[index]();
Upvotes: 1