Function pointer in C

In C, function pointer holds the address of a normal function.

Declaring a function pointer

Syntax

<return_type> (*function_pointer_name)(parameter1,parameter2);

Example

int (*myfunctionpointer)(int, int);

Initializing a function pointer

To initial a function pointer, function pointer must match the return type and parameters type and number of normal function.

Syntax

myfunctionpointer = &normal_function;

Example

#include<stdio.h>

void add(int, int);

void main()
{
    // Function pointer same as normal function add
    void (*myfunctionpointer)(int, int);
 
    // Function pointer holds address of normal function
    myfunctionpointer = &add; // Initialization

    // Calling Function pointer
    myfunctionpointer(20, 5);
    
}

void add(int a, int b) {
    int c =  a + b;
    printf("%d", c);
}
Output:
25

Passing function pointer to function as Arguments

It is one of the best application of function pointer. It allows to call multiple function as callback. Function should have same return type, parameter types and number.

#include<stdio.h>

void add(int, int);
void multiply(int a, int b);
void myfunction(int a, int b,  void (*functionpointer)(int, int)){
	functionpointer(a, b); //callback function
}
void main()
{
   myfunction(10, 5, add);
   myfunction(10, 5, multiply);
}

void add(int a, int b) {
    int c =  a + b;
    printf("\n%d", a+b);
}
void multiply(int a, int b) {
    int c =  a * b;
    printf("\n%d", c);
}

Array of Function Pointers

It allows to create an array of function pointer which holds different function addresses in different array index of function pointer.

#include <stdio.h>

// Function declarations
int sum(int a, int b) {
    return a + b;
}
int multiplication(int a, int b) {
    return a * b;
}

void main() {
    // Declare & Initialzing an array of function pointers
    int (*functionpointerarray[])(int, int) = {sum, multiplication};

    int x = 10, y = 5;

    // Dynamically call functions using the array
    printf("Sum: %d\n", functionpointerarray[0](x, y)); 
    printf("Multiplication: %d", functionpointerarray[1](x, y));
}