Function Pointer in C

Function Pointer in C

In this article, I am going to discuss Function Pointer in C with Examples. Please read our previous articles, where we discussed Dangling Pointer in C.

Function Pointer in C:

The pointer variable which holds the address of a function is called as a function pointer. The basic advantage of a function pointer is 1 function can be passed as a parameter to another function. Function pointer calls are faster than normal functions.

Syntax1: datatype(*ptr)(parameter);
Example: void(*ptr)(int);
int(*ptr)(int,int);
int(*ptr)(int);

Syntax2: datatype(*ptr)();
Example: void(*ptr)();
int(*ptr)();

Program:
#include<stdio.h>
void abc ()
{
    printf ("Hello abc \n ");
}

void main ()
{
    void (*ptr) (void);
    ptr = &abc;
    ptr ();
}

Output: Hello abc

Here in function pointer binding is not required because ptr is already pointing to the address of abc.

Program:
#include<stdio.h>
void xyz (int a, int b)
{
    printf ("sum value is: %d", a + b);
}

void main ()
{
    void (*ptr) (int, int);
    ptr = &xyz;
    ptr (10, 20);
}

Output: sum value is: 30

In the next article, I am going to discuss Pointer to Structure in C Language with Examples. Here, in this article, I try to explain Function Pointer in C. I hope you enjoy this Function Pointer in C article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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