C function pointer
What is function Pointer ?
Function pointer : A pointer which keeps address of a function is known as function pointer. [ Visit : Complete Reference Document for Function Pointer ]
Live Example :
#include<stdio.h> void display(); int main() { void *(*ptr)(); ptr = &display; (*ptr)(); return(0); } void display() { printf("Hello World"); }
Output :
Hello World
Explanation of C Snippet :
Consider normal program -
#include<stdio.h> void display(); int main() { display(); return(0); } void display() { printf("Hello World"); }
Now in the above program we have just called function display(), and we get output as “Hello World”.
Consider Scenario using pointer , We should follow following 3 steps to use pointer to call function -
- Declare Pointer which is capable of storing address of function.
- Initialize Pointer Variable
- Call function using Pointer Variable.
Step 1 : Declaring Pointer
void *(*ptr)();
- We are simply declaring a double pointer.
- Write () symbol after “Double Pointer“.
- void represents that , function is not returning any value.
- () represents that , function is not taking any parameter.
Above declaration tells us ….
Declare Pointer variable that can store address of function which does not return anything and doesn’t take any parameter
Step 2 : Initializing Pointer
ptr = &display;
This statement will store address of function in pointer variable.
Step 3 : Calling a function
(*ptr)();
using (*ptr)() we can call function display();
(*ptr)() = (*ptr)(); = (*&display)(); = (display)(); = display();
thus (*ptr)() is as good as calling function.