Pointers to Functions

A function, like a variable, has a memory location in the memory. It is therefore, possible to declare a pointer to the function, which can then be used as argument to another function. The declaration of pointer to a function is as follows:

data _ type (*func) ()

where data – type refers to the data type retuened by the function and func is the name of the function. the formal argument list can also be written.

We can declare a function pointer to point to a specific functions by simple assigning the name of the function to the pointer. For example, the statements

double (*fptr) (), func ();
fptr = func;

declare fptr as a pointer to a function and func as a function and then make fptr to point to function func. To call the function func, we many now use the pointer fptr with the list of parameter.

Program – Illustration of pointer to function

#nclude<stdio.h>
#include<conio.h>
void display ();
void (* fptr) ();
void main ()
{
    clrscr ();
    fptr = display; /*assign address of function*/
    printf (“Address of the display function is %u\n”, fptr);
    (*fptr) (); /*invokes the display () function */
    getch ();
}
void display ()
{
     printf (“inside display function. . .\n”);
}

Output

Address of the display function is 60
Inside display function. . .

In this program, a function named as display () is defined. Another pointer to function named as (*fptr) () is also defined. The statement

fptr = display;

will assign the address of the function display to fptr. Whenever the statement

(*fptr) ()

Is executed, it invokes can be passed to another function as an argument, this allows one function to be transferred another.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext