C – Function Pointers with examples

 OOPS CONCEPT

In C programming language, we can have a concept of Pointer to functions, this tutorial is to get familiar with the concept of function pointers.
How to declare Pointer to function?
<function return type>(*<Pointer_name>)(function argument list)
For example –
double  (*p2f)(double, char)
Here double is a return type of function, p2f is pointer name & (double, char) is an argument list for the function. Which means the first argument for this function should be double and the second one would be of char type.
Lets understand this with the help of an example –
#include<stdio.h>
int sum (int num1, int num2)
{
    return sum1+sum2;
}
int main()
{
    int (*f2p) (int, int);
    f2p = sum;
    int op1 = f2p (10, 13);
    int op2 = sum (10, 13);

    printf("Output 1 – for function call via Pointer: %d",op1);
    printf("Output2 – for direct function call: %d", op2);

    return 0;
}
Output:
Output 1  for function call via Pointer: 23
Output2  for direct function call: 23
You would have noticed that the output of both the statements is same –
f2p(10, 13) == sum(10, 13)
which means in generic sense you can write it out as:
pointer_name(argument list) == function(same argument list)
wherein pointer_name is declared as:
return_type(*pointer_name)(argument list); 
pointer_name = function_name(argument list);

You Might Like:


2 comments :

  1. Nice post all the fundamentals are very well explained, i will be interested to see more stuff like this, we are suggesting some of the technology related stuff check if you are looking for more information on pointers

    ReplyDelete

Please Enter best of your Comments