w3resource

C Language: Pass a function as a parameter in C language?

How to pass a function as a parameter in C?

In C language, it is possible to pass a function as a parameter to another function using function pointers.

Here is an example of how to pass a function as a parameter in C:

Code:

#include <stdio.h>

// Function to add two numbers
int add(int a, int b) {
    return a + b;
}

// Function to subtract two numbers
int subtract(int a, int b) {
    return a - b;
}

// Function that accepts a function pointer as a parameter
int calculate(int (*operation)(int, int), int a, int b) {
    return operation(a, b);
}

int main() {
    int x = 100, y = 200;
    int sum = calculate(add, x, y);
    int diff = calculate(subtract, x, y);
    printf("Sum: %d\n", sum); 
    printf("Difference: %d\n", diff); 
    return 0;
}

Output:

Sum: 300
Difference: -100

In the above example, there are two functions add() and subtract() that perform addition and subtraction of two numbers, respectively. We also have a function calculate() that accepts a function pointer operation as a parameter, along with two integers a and b. Using the function pointer operation, calculate() calls operation() with the given integers a and b.

In the main() function, we pass the add() and subtract() functions as parameters to the calculate() function using their function pointers. The calculate() function then calls the appropriate function based on the function pointer passed to it. Finally, the results are printed using printf() function.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming-exercises/c-snippets/how-do-you-pass-a-function-as-a-parameter-in-c.php