Search This Blog

Tuesday, May 13, 2025

Function Pointers in C

 A C pointer is a variable that holds the address of another variable. Can it hold the address of a function? The answer is YES. You can declare a pointer variable and store the address of a function in this variable. 

int add(int,int);

int *funptr=&add;

Or you can also assign a function name to the pointer instead.

int *funptr=add;

In C, a function name acts as a constant pointer to the function, so you can omit the & (address operator).

One of the benefits is that the same pointer variable can call different functions depending on which function it is pointing to. Using a function pointer, you can call the functions dynamically. It is useful when you want to pass a function as an argument. Here is an example:


At line 9, when you assign funptr the value of add, it stores the address of the function add and points to the function add:


When you call (*funptr)(9,7), it calls the add function and returns the sum.

At line 12, when you assign the address of the multiply function to funptr, it now points to the function multiply:


Now, on call, (*funptr)(3,9), it returns the product of numbers.

CAUTION - When you use a function pointer, it can point to different functions with the same signature (same number of parameters, same type, and order).

When the program is compiled, linked, and run, the output is:


More on function pointers, in another post...

Subscribe, share, and follow for more

Created by Nancy N.
@2:40 14-May-2025

 








No comments:

Post a Comment