Reputation: 89
I have used function pointer in my application. But recently i come across one function pointer which is called array of function pointer. I couldn't able to understand how it will work. Below is the example,
typedef uint8 (*fnHandlr)( uint16 iD, uint32 Process);
const funHandlr arr[] =
{
fun1, fun2, fun3
}
uint8 fun1(uint16 iD, uint32 Process)
{
/*Piece of code*/
}
uint8 fun3(uint16 iD, uint32 Process)
{
/*Piece of code*/
}
uint8 fun3(uint16 iD, uint32 Process)
{
/*Piece of code*/
}
my questions are below,
Upvotes: 0
Views: 76
Reputation: 726579
typedef
makes it easier for humans to "parse" the definition of the function pointer. It serves no other purpose here, because it's used only once.funHandlr
cannot be "called" because it is a type. An object of type funHandlr
(e.g. any of the array elements) can be called in the same way that you call a function pointer.arr
is the name of the array of function pointers. When you wish to call a function, apply an index to it, and then put parentheses to make the call.Here is an example of how to call one of the functions based on its index:
int index;
printf("Which function you wish to call? Enter 0, 1, or 2 >");
scanf("%d", &index);
// Make a call like this:
arr[index](myId, myProc);
What is the use of array of functions if we can
fun1
,fun2
, orfun3
directly?
Consider what would you do to write a program similar to the one above without function pointers. Here is how your code would look:
scanf("%d", &index);
switch (index) {
case 0: fun1(myId, myProc); break;
case 1: fun2(myId, myProc); break;
case 2: fun3(myId, myProc); break;
}
Apart from being repetitive and error-prone, switch
statements like this create a maintenance liability in cases when you wish to change the signature of your function. It is not uncommon for arrays of function pointers to grow to more than a hundred items; adding a new parameter to each invocation would require a lot of effort.
With an array of function pointers, however, there is only one call to change. Moreover, the readers of your code would not have to scroll through hundreds of lines in order to understand what is going on.
Upvotes: 1
Reputation: 45664
typedef
is used to simplify the declaration of the array of function-pointers.As funHandlr
is a typedef-name, it cannot be called.
Neither can the array of implicit length 3 (arr
) be called, as it is neither a function nor a function-pointer.
A value of type funHandlr
is a callable function-pointer though.
const funHandlr arr[] = { ... };
defines an array named arr
of deduced length (3, from the initializers) of const funHandlr
, funHandlr
being the type defined above.Upvotes: 1