DEV Community

Cover image for Pointer 3: (*Function Pointers) ☝️
Ridwanur Rahman
Ridwanur Rahman

Posted on

Pointer 3: (*Function Pointers) ☝️

What are function pointers?

Function pointers are like normal pointers, but they have the capability to point to a function.

Image description

Here, this is a normal function that gives the sum of two numbers. Now what the function pointer does is store the address of a function.

Image description

Here, ptr is a pointer function that stores the address of the function add.

How to declare the pointers in a function?

In the above second example, we can see that before declaring the *ptr function pointer, we used (). We could simply write *ptr(int,int)= add. But in C, operator precedence plays a role here, and () precedence is higher than *. So the function will be ptr, which declares an argument with two int types, which will eventually give an error as ptr will act as an int pointer of an integer type. For this, use (*ptr)(int,int)= add which will allow the precedence to take (*ptr) first. Let us see an example:
Image description

Declaring Array of function pointers

Like a normal array pointer , we can also declare the array of a function pointer.

Image description

If we give input 0–2, then the array of function pointers will work on the cal as it deals with the integer function. And cal is an array that stores the integer functions, and when the input num is 3, it reads the cal2[0] array of function pointers that deal with the float functions, i.e., the cal2 pointer array stores the float functions.

Passing function Pointer as Argument in a Function

Like normal data pointers, a function pointer can also be passed as an argument in a function, which will return from a function.

Image description

Here, info_int and info_char are two simple functions, where one takes integer parameters and the other takes char/string parameters. The Overall function is the pointer function, which is pointing to the functions info_int and info_char and taking two function parameters, where one is an int type with three integer parameters and the other is a string/char type with two char/string parameters.

OUTPUT

Image description

EXAMPLES

Top comments (0)