Introduction
All the functions that are defined in C are compiled into a series of instructions in the memory.
As the function is associated with the memory, we can use a pointer with a function that is associated with the first instruction function defined in the memory after the compilation process. This is an indirect method of referring to a function as a pointer by providing indirection. Indirect reference to a function in simple terms means calling the function using a function pointer which is a variable that points to that function.
Syntax
For example
The above declaration instructs the C compiler to declare a variable function_pointer, which points to a function that returns an integer. It is important to enclose the name of the function pointer in parentheses.
If we do not do this, and declare the function pointer as,
This declaration would instruct the C compiler that function_pointer is the name of a function that returns a pointer to an integer i.e. a function returning a pointer and not a variable pointing to the first instruction of the function in the memory.
Assigning the address of a function to a function pointer
To assign the address of a function to a function pointer, it is necessary to declare the function before the assignment is done.
Function pointer is the name of a pointer that would point to the first instruction of the function in the memory. The function name is the name of the function which has already been defined.
Write a program to display the address of a function.
Source Code
Output
![Output]()
Calling function using function pointer
Syntax
Source Code
Write a program to illustrate the use of a function pointer to call a function.
Output
![Management]()
The address of the function is runtime-dependent. A function can also be passed parameter.
To pass a parameter to a function pointer, we include the list of parameters after the function pointer name like.
In this declaration, we assume that function_pointer is the pointer to a function that calculates the maximum of two numbers, the values 100 and 200 are passed as parameters to the function.
Function returning a Pointer
How to pass the address of a variable to a function so that the calling function can also change the values of the parameter passed.
Write a program that illustrates a function returning a pointer.
Source Code
Output
![Address returned]()
Summary
In C, functions are compiled into a series of instructions stored in memory. By using pointers, we can reference and call these functions indirectly. A function pointer, which is a variable pointing to the function's memory location, allows for this indirect method of calling functions. This process of using a pointer to call a function is known as providing indirection.