Function Pointer in C

In C programming language, we can have a concept of Pointer to a function known as function pointer in C. In this tutorial, we will learn how to declare a function pointer and how to call a function using this pointer. To understand this concept, you should have the basic knowledge of Functions and Pointers in C.

  • Function Pointers point to code like normal pointers.
  • In Functions Pointers, function’s name can be used to get function’s address.
  • A function can also be passed as an arguments and can be returned from a function.

How to declare a function pointer?


function_return_type(*Pointer_name)(function argument list)


For example:

double (*p2f)(double, char)


Here double is a return type of function, p2f is name of the function pointer and (double, char) is an argument list of this function. Which means the first argument of this function is of double type and the second argument is char type.

Lets understand this with the help of an example: Here we have a function sum that calculates the sum of two numbers and returns the sum. We have created a pointer f2p that points to this function, we are invoking the function using this function pointer f2p.

#include <stdio.h>
int sum (int num1, int num2)
{
    return num1+num2;
}
int main()
{

    /* The following two lines can also be written in a single
     * statement like this: void (*fun_ptr)(int) = &fun;
     */
    int (*f2p) (int, int);
    f2p = sum;
    //Calling function using function pointer
    int op1 = f2p(10, 13);

    //Calling function in normal way using function name
    int op2 = sum(10, 13);

    printf("Output1: Call using function pointer: %d",op1);
    printf("\nOutput2: Call using function name: %d", op2);

    return 0;
}

Output:

Output1: Call using function pointer: 23
Output2: Call using function name: 23

Leave a Comment

Your email address will not be published. Required fields are marked *

// Sticky ads