Function Pointer in C Programming | C Tutorial

 

Learn all about function pointer in C programming language with coding, explanation and examples of functions and pointers.

Almost every function includes variables, constants and other identifiers. It is known that all of these identifiers are allocated some memory space. Therefore, every function also gets some memory allocation.

 

What Is A Function Pointer?

The function pointers are pointer variables that point to the address of a function. Similar to other pointer variables, the function pointers can be declared, assigned values and used to access the functions which they point to.

A pointer to a function points to the initial portion of the executable code of the function. It points to code and not the data.

Syntax

Declaring a Function Pointer

In order to declare a pointer to a function, we have to declare it like the prototype of the function except that the name of the function is enclosed in parentheses and an asterisk is inserted before the name.

In function pointer declaration above, we declare a pointer to a function that returns an integer value and accepts two arguments – one of type integer and the other of type float.

Because of precedence of operators, if you do not put the function name within parentheses, you will end up declaring a function returning a pointer as shown below:

When a pointer to a function is declared, it can be called using one of the following forms:

Note: This C function pointer coding example is compiled with GNU GCC compiler using CodeLite IDE on Microsoft Windows 10 operating system.

C Program For Arithmetic Operations using Function Pointer

   

Output

Function Pointer in C Programming completely explained with output, code and explanation

How To Pass A Function Pointer As An Argument To A Function?

A function pointer can be passed as the calling argument of a function and can also be returned from a function. This is, in fact, necessary if you want to pass a pointer to a callback function. Let us see an implementation below.

Array of Function Pointers

When an array of function pointers is made, the appropriate function is selected using an index.

Step 1: Use typedef keyword so that function_pointer can be used as type:

Step 2: Define the array and initialize each element to NULL. This can be done in the following ways:

Step 3: Assign the function’s address – Add, Subtract, Multiply and Divide

Step 4: Call the function using an index to address the function pointer

Let us see a complete implementation of array of function pointers in C programming below.

   

If you have any doubts about function pointer in C programming, let us know about it in the comment section. Find more about it here.

MORE ON POINTERS
Null Pointers
Void Pointers
Wild Pointers
Dangling Pointers
Huge Pointers
Near Pointers
Far Pointers

Let's Discuss