w3resource

C Language: Function pointers in C with example

How do function pointers work in C?

In C, a function pointer is a variable that stores the address of a function.
A function pointer can be used to pass a function as an argument to another function, or to call a function dynamically.

Here is an example:

#include <stdio.h>
int add(int x, int y, int z) {
    return x + y +z;
}
int multiply(int x, int y, int z) {
    return x * y *z;
}
int main() {
    int x = 10, y = 20, z = 30;
    int (*func_ptr)(int, int, int); // function pointer variable declaration

    // assign the address of add function to function pointer
	func_ptr = &add; 
    // calling add function using function pointer
	printf("Addition: %d\n", (*func_ptr)(x, y, z)); 

    // assign the address of multiply function to function pointer
	func_ptr = &multiply; 
	// calling multiply function using function pointer
    printf("\nMultiplication: %d\n", (*func_ptr)(x, y, z)); 
    return 0;
}

Output:

Addition: 60

Multiplication: 6000

In the said example, we declare two functions add and multiply, which take three integer arguments and return an integer value. We then declare a function pointer variable func_ptr that can point to any function that has the same signature as add, and multiply.

In main() function, we assign the address of the add() function to func_ptr, and use the function pointer to call add with arguments x, y and z. Finally, we assign the address of the multiply() function to func_ptr, and use the function pointer to call multiply with arguments x, y and z.



Follow us on Facebook and Twitter for latest update.