How to use Function Pointer in C

In this article, we are going to learn How to use Function Pointer in C language. This article also covers how to use function pointers in C, how to declare function pointers in C, how to call a function using function pointers in C with examples. If we are curious to learn this then follow step by step in this post.

What is function pointer in C


A pointer that points to any function is called a Function Pointer. It points to a specific part of code but a normal pointer points to a specific variable in code. The most valuable thing is that we can pass the function parameter as an argument to another function and its name can be used to get the address of the function.

Syntax of Function Pointer

returntype ( *Pointer_name) ( argument_list)

//Example:
int ( *funct_pointer_add ) ( int,int );

Parameters

  • In the above syntax funct_pointer_add is a pointer to a function taking two integers as argument that will return an integer.

How to use Function Pointer in C program


In this c program, we have defined a function Add() that takes two arguments. In this main() function define functiontopointer that points to the add() function.This is how we define a function pointer and use it.

include <stdio.h>
int Add(int var1, int var2)
{
   return var1 + var2 ;
}


int main ()
{
    int ( *functiontopointer ) (int, int) ;
    functiontopointer = Add ; 


    int SumResult = functiontopointer(10, 5) ;

    int SumResult1 = Add(10, 5) ;

    printf ( "The Sum Result from Function Pointer call : %d " , SumResult ) ;
    printf ( " \nThe Sum Result from Normal function call: %d " , SumResult1 ) ;
    return 0 ;
}

Output

The Sum Result from Function Pointer call : 15  
The Sum Result from Normal function call: 15

Arithmetic operation using function pointer in C


Now let us see some more example C programs of arthmetic operations using function pointers. In this example, we are making an array of function pointers and assigning separate functions to each index of the array. Then we are using each index pointer to call each function.

#include <stdio.h>

void Add ( int Num1 , int Num2 )
{
   printf ( "The addition of Given Numbers is: %d \n " , Num1 + Num2 ) ;
}

void Subtract( int Num1 , int Num2 )
{
  printf ( "The Substraction of Given Numbers is:  %d\n " , Num1 - Num2 ) ;
}


void Multiply ( int Num1 , int Num2 )
{
  printf ( "The Multiplication of Given Numbers is:  %d\n " , Num1*Num2 ) ;
}

int main()
{
    void ( *funcpointer_arr[] )( int , int ) = { Add, Subtract, Multiply } ;

    int Num1 = 10, Num2 = 5 ;


    ( *funcpointer_arr [0] ) ( Num1 , Num2 ) ;
    ( *funcpointer_arr [1] ) ( Num1 , Num2 ) ;
    ( *funcpointer_arr [2] ) ( Num1 , Num2 ) ;

     return 0 ;
}

Output

 The addition of Given Numbers is: 15 
 The Substraction of Given Numbers is:  5
 The Multiplication of Given Numbers is:  50