![]() |
VOOZH | about |
In C, a function pointer is a type of pointer that stores the address of a function, allowing functions to be passed as arguments and invoked dynamically. It is useful in techniques such as callback functions, event-driven programs, and polymorphism (a concept where a function or operator behaves differently based on the context).
Let's take a look at an example:
15
Explanation: In this program, we define a function add(), assigns its address to a function pointer fptr, and invokes the function through the pointer to print the sum of two integers.
Function pointers are declared according to the signature of the function they will be pointing to. Below is the generic syntax of function pointer declaration:
The parenthesis around the pointer_name is necessary, otherwise, it will be treated as a function declaration with the return type of return_type* and name pointer_name.
The type of the function is decided by its return type, number and type of parameters. So, the function pointer should be declared in such a way that it matches the signature of the function it later points to. For example, in the above code, the function pointer was declared as:
which matches the signature of the add() function that it later points to.
A function pointer is then initialized by assigning the address of the function.
We can also skip the address of operator as function name itself behaves like a constant function pointer.
It is compulsory to assign the function with similar signature as specified in the pointer declaration. Otherwise, the compiler may show type mismatch error.
Function pointer points to the code instead of the data so there are some restrictions on the function pointers as compared to other pointers. Following are some important properties of function pointer:
The following programs lists some common applications of function pointers along with code examples:
One of the most useful applications of function pointers is passing functions as arguments to other functions. This allows you to specify which function to call at runtime.
15 5
Explanation: The calc function accepts a function pointer operation that is used to perform a specific operation (like addition or subtraction) on the two integers a and b. By passing the add or subtract function to calc, the correct function is executed dynamically.
We can create a data member inside structure, but we cannot define a function inside it. But we can define function pointers which in turn can be used to call the assigned functions.
Rectangle's Width: 10, Height: 5 Rectangle Area: 50
You can also use function pointers in arrays to implement a set of functions dynamically.
Sum: 15 Difference: 5 Product: 50 Divide: 2