Function Pointer in C

Function Pointer in C

Function pointer known as Pointer to a function.The code of a function always resides in memory, which means that the function has some address and we can get the address of memory by using the function pointer.

Function Pointer in C

 

Declaration of Function pointer

The function pointer name is preceded by the indirection operator ( * )

return type (*ptr_name)(type1, type2…);

 

Example 1

int (*pt) (int);

Here, *pt is a pointer that points to a function that returns an int value and accepts an integer value as an argument.

 

Example 2

float (*ft) (float);

Here, *ft is a pointer that points to a function that returns an int value and accepts a float value as an argument.

Program

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

Also, read the Break and continue in C

 

Share this post

Leave a Reply

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