C

Function Pointer In C With Examples

In the C programming language, there is a concept known as function pointer, which is a pointer to a function. In this tutorial, we will learn how to declare a function pointer and how to use it to call a function. To grasp this concept, you should be familiar with Functions and Pointers in C.

What is the syntax for declaring a function pointer?

function_return_type(*Pointer_name)(function argument list)

For example:

double  (*p2f)(double, char)

Here, double is the function’s return type, p2f is the function pointer’s name, and (double, char) is the function’s argument list. This means that the first argument to this function is of type double, and the second argument is of type char.
Let’s look at an example to see what I mean: We have a function sum here that computes and returns the sum of two numbers. We have created a function pointer f2p that points to this function, and we are invoking it with this function pointer f2p.

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

Some thoughts on function pointers:
1. As mentioned in the comments, you can declare a function pointer and assign it to a function in a single statement, as shown below:

void (*fun_ptr)(int) = &fun;

2. You can even omit the ampersand from this statement because a function name represents the function address on its own. This means that the preceding statement can also be written as follows:

void (*fun_ptr)(int) = fun;

Related Articles

Leave a Reply

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

Back to top button