What is function pointer and how to use function pointer?

A function pointer is a variable which is used to hold the starting address of a functions and the same can be used to invoke a function. It is also possible to pass address of different functions at different times thus making the function more flexible and abstract.

So the function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values. Function pointers do always point to a function having a specific signature. Thus, all functions used with the same function pointer must have the same parameters and return type


ReturnType (*PtrToFun)(arguments if any)


#include "stdio.h"
void my_int_func(int x)
    printf( "%d\n", x );
int main()
    void (*foo)(int);
    /* the ampersand is actually optional */
    foo = &my_int_func;
    return 0;

In above example function pointer foo is used to call the function my_int_func.

Uses of Function Pointers

Pointer to function is useful when you want to choose a function dynamically at run time – usually based on certain conditions. Function Pointers are used to implement generic functions like qsort(), callbacks, state machines and anywhere else run time binding of a function is required. Also Function pointers are used to store interrupt handlers in tables.

To begin, check out the qsort fucntion

void qsort(void *base, size_t nmemb, size_t size, 
           int (*compar)(const void *, const void *));

Here, you need to pass a pointer to the function that compares the objects that you are sorting. Since qsort() is a generic implementation and does not care what you are sorting, it is up to you to implement a funtion which compares the objects that you are sorting and pass it on to qsort(). qsort() just invokes your compare function by dereferencing the function pointer.

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

2 thoughts on “What is function pointer and how to use function pointer?

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.