Use of function pointer in c

function pointer in c

Misunderstanding of the fundamental concept of function pointer can create hidden issues in your project and takes a lot of time in resolving. These hidden issues can become the main cause of the failure of the project.




A function pointer is one of the most important pointer tools which is often ignored and misunderstood by the people. Generally, people face the problem with function pointer due to an improper declaration, assignment and dereferencing the function pointer.

A function pointer is one of the most important and difficult topics in c language. Only a few people understand the proper utilization of function pointer.

What is function pointer?

A function pointer is similar to the other pointers but the only difference is that it points to a function instead of the variable.
In the other word, we can say, a function pointer is a type of pointer that store the address of a function and these pointed function can be invoked by function pointer in a program whenever required.

aticleworld

Declaration of function pointer in c

The syntax for declaring function pointer is very straight forward. It seems like difficult in beginning but once you are familiar with function pointer then it becomes easy.

The declaration of a function pointer is similar to the declaration of a function. That means function pointer also requires a return type, declaration name, and argument list. One thing that you need to remember here is, whenever you declare the function pointer in the program then declaration name is preceded by the * symbol and enclosed in parenthesis.

For example,  void ( *fpData )( int )

For the better understanding, let’s take an example to describe the declaration of a function pointer in c.
e.g,
void ( *pfDisplayMessage) (const char *);

In above expression, pfDisplayMessage is a pointer to a function taking one argument, const char *, and returns void.

When we declare a function pointer in c then there is a lot of importance of the bracket. If in the above example, I remove the bracket, then the meaning of the above expression will be changed and it becomes void *pfDisplayMessage (const char *). It is a declaration of a function which takes the const character pointer as arguments and returns void pointer.



List of some function pointers

A function pointer must have the same signature to the function that it is pointing to. In a simple word, we can say that function pointer and its pointed function should be same in parameters list and return type.

So there can be a lot of possibility of function pointer in c. In below section, I am listing some function pointers and I want you to write the name of these function pointers in a comment box.

 

Initialization of function pointer in c

We have already discussed that a function pointer is similar to normal pointers. So after the declaration of a function pointer, we need to define it like normal pointers.

A function pointer is initialized to the address of a function but the signature of function pointer should be same as the function.

For example, here I am creating a function pointer taking two arguments, integers and returns an integer. This pointer is pointing to a function AddTwoNumber is used in addition of two number.

Let’s take a look at the below declaration.

declaration of function pointer

int (* pfAddTwoNumber) (int, int);

Initialize the function pointer with the address of AddTwoNumber

pfAddTwoNumber = & AddTwoNumber;
                                         or
because the function name also represents the beginning address of the function, so we can also use the function name to initialize the function pointer.

pfAddTwoNumber = AddTwoNumber;

We can also initialize the function pointer in a single line.

int (* pfAddTwoNumber) (int, int) = AddTwoNumber;

 

Some Important points for the function pointer

Memory allocation and deallocation for function pointer

We cannot allocate or deallocate memory for the function pointer as like the normal pointers. The aim of the creation of function pointer is to point the beginning address of the function. So if you allocate the memory for the function pointer then there is no importance to create the function pointer.

void (*pfData) (int)  = malloc(sizeof(pfData));  // Not useful expression

Assigning function address to function pointer

The function name is also used to get the address of the function, that means in a program we can also use the function name to get the address of the function there is no need to write & operators with the function name.

pfAddTwoNumber = AddTwoNumber;
or
pfAddTwoNumber = &AddTwoNumber;

Calling a function using the function pointer

After the initialization of function pointer, we can call the function using the initialized function pointer. For your understanding, I am breaking the function calling through a pointer in a few steps.

  • First, write the name of a function pointer.
    pfAddTwoNumber;
  • We know that function pointer is also similar to another pointer but the only difference is that function pointer pointed to a function except for the variable. So we put the * as a prefix to the name of function pointer to take the value of the function pointer.
    *pfAddTwoNumber;
  • Finally, we have a function. For the function calling just simply add the arguments list with extra parenthesis to the above expression.
    (*pfAddTwoNumber)(10, 20);

For the better understanding, I am taking an example, where I am calling a function using the function pointer. This function is used to add the value of two integers.

OutPut:

Explanation of the above program

In the above program first I am declaring a function pointer pfAddTwoNumber in main ().

int (*pfAddTwoNumber) (int,int);

This declaration explains that the function pointer can be a point to the function which takes two augments integer and return an integer.
After the declaration of the function next step is to initialize the function pointer.

pfAddTwoNumber = AddTwoNumber;

After the assignment address of AddTwoNumber to the function pointer pfAddTwoNumber, a function can be called with the help of the function pointer.

iRetValue = (*pfAddTwoNumber)(10,20);

                                                     or
iRetValue = pfAddTwoNumber(10,20);

Note: Syntax of function pointer is very flexible, you may omit the * symbol and & from the syntax of function calling and function address.

Comparing of a function pointer

We can also use the comparison operators (== or != ) with function pointer. These operators are very helpful to check if the function pointer is initialized or not.

Before calling a function pointer in the program you must check its validity and it is very good practice to check the validity of function pointer.

In your program, if the function pointer is not initialized by the valid address and your application wants to execute the function pointer then you will get BSOD (Blue screen of death ) or system hangs issues.

So before the function calling checked the validity of pointers using conditional    ( != NULL ).
For Example,
Here, pfLedOnOff is a function pointer, which is called to make led On or Off.




Function pointer as arguments

In the c language, we can pass the function pointer as an argument into the function like the other pointers. Let’s take an example to understand how to pass a function pointer in a function. I am writing an example code.

In below code, ArithMaticOperation is a function that takes three arguments two integers, and one function pointer. The function pointer is pointed to a function that takes two integers as arguments and returns an integer.

In the example code, there are three functions that perform the addition, subtraction, and multiplication operation. We can pass these function in ArithMaticOperation as the argument to perform the operation on integer as per the user choice.

 

OutPut:

Return a function pointer from the function

In the c, a function can return the function pointer like the normal pointers. For the better understanding, I am writing an example which describes how to return a function pointer in c.

OutPut:

 

Use of array of function pointers

The array of function pointer is very interesting and similar to the normal array of pointers. The array of function pointers offers the facility to access the function using the index of the array.

Let’s take an example, I am creating an array of a function pointer, pointers pointed to a function takes two integers as arguments and returns the integer.

In below example, apfArithmatics is an array of function pointers. These functions perform the arithmetic operation like addition, subtraction and multiplication.

OutPut:

Use of typedef with the function pointer

Using typedef, we can make the declaration of an array of function pointers easy.
For example,
In above example, I have used a complex expression for the declaration of the array of function pointers. Using typedef, we can make it easier.

// typedef of array of function pointers
typedef int (*apfArithmatics[3])(int,int);

Now, apfArithmatics is a new data type and it is able to store the address of three functions.

apfArithmatics aArithmaticOperation = {AddTwoNumber,SubTwoNumber,MulTwoNumber};



Declare function pointers in structure

C is not an object-oriented language, so it does not contain the member functions like C++. In the c language, a structure does not contain the functions, only contains the data. We can store a function within the structure using the function pointers and these function pointers are treated like a member function in C++.
For example,

 

Related: how to use the function pointer in structure.

Function pointer as callback function

For windows, in a kernel mode driver (KMDF), we use a lot of call back function for the plug and play and device preparation. Each callback function is invoked by the operating system at specific events but we need to register call back function using the function pointer.

Let’s take an example, suppose there is a callback function MyUsbEvtDevicePrepareHardware. In this callback function, the driver does whatever is necessary to make the hardware ready to use. In the case of a USB device, this involves reading and selecting descriptors.

Function pointer use to register the above call-back function

We know that the name of the function is the beginning address of the function, so we can initialize the function pointer using the function name.

pfPrepareHardware = MyUsbEvtDevicePrepareHardware;

Now we can use pfPrepareHardware for the registration of MyUsbEvtDevicePrepareHardware.

Your opinion matters

Although here I have tried to discuss a lot of points regarding the function pointer but I would like to know your opinion on the function pointer in structure. So please don’t forget to write a comment in the comment box.



5 comments

  1. Nice information about fn PTR…this meterial solved most doubts…tq u… And one more request….if u hv material about “call back fn” ….lk wht is call back fn…how to use ….
    Plz frwd my mail id:[email protected]

Leave a Reply