Function Pointers in C

May 15, 2021 0 Comments

Function Pointers in C

Function Pointers in C, Function pointers can be useful when you want to create a callback mechanism and need to pass the address of a function to another function. They can also be useful when you want to store an array of functions, to call dynamically. Formally Syntax is

type (*fun_pointer)(argument_type list);

Example:

float (*fp) (char , float);

Here float is a return type of function, fp is the name of the function pointer, and (char, float) is an argument list of this function. This means the first argument of this function is of char type and the second argument is float type.

int (*fp)(int,int);

– fp is pointer to function which returns an integer and takes two integers as arguments.

char (*fp)(int, int);

-fp is pointer to function which returns an character and takes two integers as arguments.

Q) Define a function that will take two integer pointers as arguments and return integer pointer?

Ans: int * (*fp)(int *, int *);

Q) Define a function that will take two void pointers as arguments and return void pointer?

Ans: void *(*fp)(void *, void *);

Function pointer Example Code:

#include<stdio.h>
int (*fp)(int,int);    // fp is pointer to function
int add(int x, int y) {
        return x+y;
}

int sub(int x, int y) {
        return x-y;
}

int main() {
        int i;
        fp = add;              // Initializing fp with address add function
        i = (*fp)(10,20);      // Calling add function using fp
        printf("add: %d \n",i);
        fp = sub;
        i = (*fp)(20,10);
        printf("sub: %d \n",i);
        return 0;
}

Array of function pointers:

Function Pointers in C, Example of Array of function pointers

#include<stdio.h>
int (*fp[2])(int,int);      // fp is array of 2 pointer to functions
int add(int x, int y) {
	return x+y;
}
	
int sub(int x, int y) {
    return x-y;
}

int main() {
    int i;
    fp[0] = add;
    i = (*fp[0])(10,20);      // calling add function
    printf("add: %d \n",i);
    fp[1] = sub;
    i = (*fp[1])(20,10);      // calling sub function
    printf("sub: %d \n",i);
    return 0;
}

Typedef for Function Pointers:

We can use typedef to simplify the usage of function pointers.

Syntax:

typedef data_type (*func_ptr_name)(arg_list);

Example:

int add(int x, inty) {

return x+y;

}

typedef int (*add_t) (int, int);

add_t a = &add;

int z = a(10, 20);

Share This: