Advertisement
Guest User

function pointer as argument

a guest
Jan 27th, 2023
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*In C, functions can be passed as parameters by using function pointers. A function pointer is a variable that stores the memory address of a function, and can be used to call the function just like a regular function.
  2. In C, functions can be passed as parameters by using function pointers. A function pointer is a variable that stores the memory address of a function, and can be used to call the function just like a regular function.
  3. In this example, the add function is defined as a regular function that takes two integers as parameters and returns their sum. The call_function function takes a function pointer as its first parameter, followed by two integers. Inside the call_function function, the passed function pointer is called with the two integers as arguments, and the result is printed.
  4.  
  5. In the main function, we pass the add function to the call_function function as a parameter, along with the values 3 and 4. When the call_function function is called, it calls the add function with the values 3 and 4, and prints the result of 7.
  6.  
  7. It's worth noting that in C, function pointers do not include information about the argument types, so you need to make sure that the function pointer's type matches the function you are passing. Additionally, C does not have function overloading, so you need to use different names for functions that take different parameter types or different number of parameters. */
  8.  
  9. #include <stdio.h>
  10.  
  11. // function to be passed as parameter
  12. int add(int a, int b) {
  13.     return a + b;
  14. }
  15.  
  16. // function that takes a function pointer as parameter
  17. void call_function(int (*func)(int, int), int a, int b) {
  18.     int result = func(a, b);
  19.     printf("Result: %d\n", result);
  20. }
  21.  
  22. int main() {
  23.     // pass the add function as parameter
  24.     call_function(add, 3, 4); // prints "Result: 7"
  25.     return 0;
  26. }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement