C Function Pointer

Simple Example of Function Pointer

Let's consider a scenario to demonstrate the concept of function pointers in the C programming language.

Example

Example

#include <stdio.h>  

int main()   //main function

{  

    printf("Address of main() function is %p",main);  

    return 0;  

}

Output:

Output

Address of main() function is 0x5aa2c1954149

Explanation:

In the preceding result, we notice that the main method possesses a particular location. Consequently, we can infer that each function is associated with a distinct address.

Declaration of a function pointer

In the C programming language, a function pointer is employed to hold the memory address of a function and enables indirect function invocation. When declaring functions with addresses, pointers capable of storing these addresses can be defined.

Syntax of function pointer

Example

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

For example:

Example

int (*ip) (int);

Explanation:

In the declaration provided, the *ip is a pointer pointing to a function that returns an integer value and takes an integer value as a parameter.

Syntax for floating point:

Example

float (*fp) (float);

Explanation:

In the aforementioned declaration, *fp represents a pointer pointing to a function that outputs a floating-point value and takes a floating-point value as input.

It can be noted that defining a function is akin to defining a function pointer, with the distinction that the pointer is denoted by a '*'. Therefore, in the provided declaration, "fp" is defined as a function and not as a pointer.

So far, we have acquired the knowledge of declaring a function pointer. Our subsequent task involves assigning the memory location of a function to the function pointer.

Example

float (*fp) (int , int);    // Declaration of a function pointer.  

float func( int , int );    // Declaration of  function.  

fp = func;                     // Assigning address of func to the fp pointer.

In the declaration above, the 'fp' pointer stores the memory address of the 'func' function.

Initialization

In the C programming language, a function pointer is set by storing the memory address of the function.

Example

fp = &function_name

We can circumvent the need for the address of the operator by utilizing the function name as a constant function pointer.

Example

fp = function_name;

It is essential to associate the function with an identical signature as specified in the pointer declaration. Failure to do so will result in the compiler generating a type mismatch error.

Calling a function through a function pointer

We are familiar with invoking a function conventionally. Next, we will explore invoking a function by utilizing a function pointer.

Suppose we declare a function as given below:

Example

float func(int , int);      // Declaration of a function.

Invoking a preceding function using a typical method is illustrated below:

Example

result = func(a , b);     // Calling a function using usual ways.

Invoking a function through a function pointer is illustrated below:

Example

result = (*fp)( a , b);    // Calling a function using function pointer.
Example

result = fp(a , b);      // Calling a function using function pointer, and indirection operator can be removed.

The impact of invoking a function by its name versus a function pointer remains identical. When utilizing the function pointer, we have the option to exclude the indirection operator, as demonstrated in the latter scenario. However, it is advisable to retain the indirection operator to explicitly indicate to the user that a function pointer is being utilized.

Function Pointer Example in C

Let's consider an example to demonstrate the concept of function pointers in the C programming language.

Example

Example

#include <stdio.h>  

int add(int,int);  

int main()    //main function

{  

   int a,b;  

   int (*ip)(int,int);  

   int result;  

   printf("Enter the values of a and b : ");  

   scanf("%d %d",&a,&b);  

   ip=add;  

   result=(*ip)(a,b);  

   printf("Value after addition is : %d",result);  

    return 0;  

}  

int add(int a,int b)  

{  

    int c=a+b;  

    return c;  

}

Output:

Output

Enter the values of a and b : 5

26

Value after addition is : 31

Explanation:

In this illustration, we showcase the utilization of a function pointer to execute the add function. In this scenario, we define the pointer ip to hold the location of add, and the function is indirectly triggered by (*ip)(a, b) to carry out the addition operation.

Imitate Member Functions in Structure

We have the capability to specify a data member inside the structure, but we are restricted from defining a function within it. Nevertheless, we do have the option to declare function pointers within the structure, allowing us to subsequently invoke the specified functions.

Example

Example

#include <stdio.h>

#define PI 3.14159

typedef struct Circle {

    float radius;

    void (*setRadius)(struct Circle*, float);

    float (*getArea)(struct Circle*);

    void (*display)(struct Circle*);

} Circle;

void setRadius(Circle* c, float r) {

    if (r < 0) {

        printf("Invalid radius. Must be non-negative.\n");

        return;

    }

    c->radius = r;

}

float getArea(Circle* c) {

    return PI * c->radius * c->radius;

}

void display(Circle* c) {

    printf("Circle Radius: %.2f\n", c->radius);

}

void initCircle(Circle* c) {

    c->radius = 0.0f;

    c->setRadius = setRadius;

    c->getArea = getArea;

    c->display = display;

}

int main() {  //main function

    Circle c1;

    initCircle(&c1);  

    c1.setRadius(&c1, 6);

    c1.display(&c1);

    printf("Circle Area: %.2f\n", c1.getArea(&c1));

    return 0;

}

Output:

Output

Circle Radius: 6.00

Circle Area: 113.10

Explanation

In this instance, we define a Circle construct containing a float radius and function pointers to mimic object-oriented behaviors like methods. Subsequently, we create the setRadius, getArea, and display functions to establish a radius, compute the area, and exhibit the radius value. The initCircle function is responsible for initializing a Circle instance and configuring its function pointers. Within the primary function, a Circle instance is instantiated and configured, a radius of 6 is allocated, information is presented, and the area is exhibited.

Passing a function's address as an argument to another function

We have the ability to pass the memory location of a function as a parameter to other functions just like we pass regular arguments to a function. This concept can be illustrated using an example.

Example

Example

#include <stdio.h>  

void func1(void (*ptr)());  

void func2();  

int main()   //main function

{  

    func1(func2);  

     return 0;  

}  

void func1(void (*ptr)())  

{  

    printf("Function1 is called");  

    (*ptr)();  

}  

void func2()  

{  

    printf("\nFunction2 is called");  

}

Output:

Output

Function1 is called

Function2 is called

Explanation:

In this illustration, we have established two functions, namely, func1 and func2. The func1 function includes a function pointer as a parameter. Within the main function, the func1 function is invoked, passing the reference of func2. Upon calling the func1 function, 'ptr' holds the reference of 'func2'. Within the func1 function, we invoke the func2 function by dereferencing the pointer 'ptr', which stores the reference of func2.

Array of Function Pointers

In the realm of C programming, function pointers are employed in scenarios where the specific function to be executed is not predetermined. Within an array of function pointers, the array stores the memory addresses of various functions, allowing for the execution of the appropriate function based on the corresponding index number.

Array of Function Pointers Example

Let's consider an instance to demonstrate the array of function pointers in the C programming language.

Example

Example

#include <stdio.h>  

float add(float,int);  

float sub(float,int);  

float mul(float,int);  

float div(float,int);  

int main()    //main function

{  

    float x;      // variable declaration.  

    int y;  

    float (*fp[4]) (float,int);        // function pointer declaration.  

    fp[0]=add;     // assigning addresses to the elements of an array of a function pointer.  

    fp[1]=sub;  

    fp[2]=mul;  

    fp[3]=div;  

    printf("Enter the values of x and y : ");  

    scanf("%f %d",&x,&y);  

  float r=(*fp[0]) (x,y);        // Calling add() function.  

    printf("\nSum of two values is : %f",r);  

     r=(*fp[1]) (x,y);             // Calling sub() function.  

    printf("\nDifference of two values is : %f",r);  

      r=(*fp[2]) (x,y);            // Calliung sub() function.  

    printf("\nMultiplication of two values is : %f",r);  

     r=(*fp[3]) (x,y);           // Calling div() function.  

    printf("\nDivision of two values is : %f",r);  

    return 0;  

}  

  

float add(float x,int y)  

{  

    float a=x+y;  

    return a;  

}  

float sub(float x,int y)  

{  

    float a=x-y;  

    return a;  

}  

float mul(float x,int y)  

{  

    float a=x*y;  

    return a;  

}  

float div(float x,int y)  

{  

    float a=x/y;  

    return a;  

}

Output:

Output

Enter the values of x and y : 5

7



Sum of two values is : 12.000000

Difference of two values is : -2.000000

Multiplication of two values is : 35.000000

Division of two values is : 0.714286

Explanation:

In this instance, we've established an array of function pointers holding the memory addresses of four functions. Following the storage of function addresses in the function pointer array, we proceed to invoke the functions through the function pointers.

Functions with void Pointers

In C programming, void pointers (void) are employed when declaring functions. A void return type enables the return of any type. Nonetheless, a function cannot return void * and automatically convert it to any type without a specific cast.

If data is supplied to the function, it must remain unchanged, and the parameter can be defined as a constant void pointer, safeguarding the data against unintentional alterations.

Functions with Void Pointers Example

Let's consider a scenario to demonstrate the usage of void pointers in the C programming language.

Example

Example

#include <stdio.h>

int square(const void* num) {

    int val = *(const int*)num;

    return val * val;

}

int main() {   //main function

    int n = 9;

    int sq = square(&n);

    printf("Square of %d is %d\n", n, sq);

    return 0;

}

Output:

Output

Square of 9 is 81

Explanation:

In this instance, we define a function named "square" which takes in a constant void pointer, converts it to an integer pointer, and calculates the square of the integer it references. Within the main function, the square function is invoked with the memory address of an integer variable 'n' and displays the resulting squared value. This demonstration illustrates the utilization of void pointers to enable a generic function to operate with integers.

Conclusion

In summary, function pointers in C enable the dynamic invocation of functions by storing their memory addresses. They enhance code flexibility and modularity by allowing tasks such as emulating object-oriented programming with structures, passing functions as arguments, and managing arrays of function pointers for dynamic function resolution. The utilization of void* pointers within functions supports the creation of generic functions capable of operating on diverse data types.

Input Required

This code uses input(). Please provide values below: