C Programming language

adplus-dvertising
Pointers to Functions
Previous Home Next

The function pointer is a powerful feature in c. In memory a function has a physical location that can be assigned to a pointer. This address is the entry point of the function and it is the address used when the function is called. Once a pointer points to a function, the function can be called through that pointer. Function pointers also allow functions to be passed as arguments to other functions or function pointers is a pointers, that point to the address of a function.

Now we can se that when we run the any program than that running program gets a certain space in the main-memory. than the executable compiled program code and variables are put inside this memory. Thus that program code have a functions than that function in the program code is, like e.g. a character field, nothing else than an address. It is only important how you, or better your compiler/processor, interpret the memory a pointer points to.

#include<stdio.h>
#include<conio.h>
void my_int_func(int x)
{
    printf( "%d\n", x );
}
int main()
{
    void (*yes)(int);
    yes = &my_int_func; 
/* call my_int_func (note that you do not need to write (*yes)(2) ) */
    yes( 2 );
    /* but if you want to, you may */
    (*yes)( 2 );

    return 0;
};

Output: The output of the above program would be:

2 2

Example

#include<stdio.h> 
   #include<conio.h> 
   int show(); 
   void main() 
  
   int (*fP)(); 
   clrscr(); 
   fP=show; 
      printf("Address of function :%u",show); 
       (*fP)(); 
       getch(); 
  
    
   int show() 
  
   printf("\nFunction called using pointer!"); 
   return 0
   }

Output: The output of the above program would be:

Address of function : 694

Function called using pointer!

Previous Home Next