Join Regular Classroom : Visit ClassroomTech

Pointer to a function in C

Function pointer is used to store the address of a function, we can call the function later through this function pointer. This is a useful process because for any particular work like drawing a line we have to write a huge code. Instead of that we can call a function through function pointer.

Syntax:

return_type  *(function_name)(data_type)

Example:

void *(fun)(int)

Explanation: In this example, fun is a pointer to function taking one argument of integer datatype and it’s return type is void.
Like in int *x, *x is an int and x is a pointer to an int similarly, here fun is a pointer to a function and *(fun) is a function

/* C program to understand Function pointer */
/* www.codewindow.in */

#include <stdio.h>
void the_int_func(int a) {
    printf("%d\n", a);
}
 
// Driver code
int main() {
    void (*fun)(int);
    fun=&the_int_func;		// Assigning the address of the func to the pointer variable
 
    /* Call the_int_func ( no need to write (*fun)(2) ) */
    fun(5);
    /* But it can also be written */
    (*fun)(5);
 
    return 0;
}

Output

5

Explanation
The address of the “the_int_fun” function is assigned to the pointer variable “fun”. Thereafter calling the pointer with an argument value will return the outcome of the function.


Follow Us


You Missed

Also Checkout