Hello Friends,
How can I use an array of function pointers?
If we will see the above link, it tells us how function pointer works.
Now the question is why should I choose function pointer?
Why can't I use function call directly?
What are the benifits will I get with function pointer?
e.g
enum{a, b, c};
void A();
void B();
void C();
void (*fun[3])() = {A, B, C};
Now when I need to call a function I am doing like,
fun[a](); // This calls function A
// And so on...
Same can be done in function calls also
like when I need to call function A, B or C. directly I can right like
A();
B();
or
C();
Then why function pointer
?
1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code. 2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers. 3) A function's name can also be used to get functions' address.
Difference between Function Pointer and Callback FunctionsA function pointer is a pointer that points to the function. Whereas, callback functions are function pointers passed as parameters of the function, which can be called back when an event occurs.
As I understand function pointer is a pointer variable that stores address of a function however pointer to a function is a function which takes function pointer as an argument.
A function pointer is a pointer variable, but it holds the address of a function, not the address of a data item. The only things you can do with a function pointer are read its value, assign its value, or call the function that it points toward.
Now the question is why should I choose function pointer?
What are the benifits will I get with function pointer?
You use function pointers when you need to implement a Asynchronous mechanism.
You need a function be called asynchronously when something happens.
How will you know which function to call?
The address of every function is Unique,So you need to use and store the function address.
Where do you store this function address?
A function pointer
In my experience, function pointers are mainly used to pass a function as a parameter to another function.
Looking at your code, they could also be used like with arrays, so you can just loop through the entire array (which could consist of hundreds of function pointers) and it will just execute them all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With