Sometimes a function needs to be defined in such a way that it can receive a function as a parameter. As, in C language, a function is defined with a specific signature (because it does not support function overloading), the function (ex. function funman(...) in the following example) can receive those functions, which are defined following the same signature, as parameter (ex. add(...) and mul(...) in the following example).
In the following example, the function funman() can receive those functions as parameters that are defined for taking two integer parameters. The functions add() and mul() take two integer parameters. Thus, the functions add() and mul() can be sent as parameters to the function funman(). However, the function add3() can not be passed as an argument to the function funman().
Example code for passing function to a function as parameter
#include <stdio.h>
#include <stdlib.h>
int funman(int (*) (int x, int y), int x, int y);
int add(int x, int y);
int add3(int x, int y, int z);
int mul(int x, int y);
int main(void)
{
int i, j, res;
printf("Enter two integer numbers: ");
scanf("%d %d", &i, &j);
res = funman(add, i, j);
printf("\nres is : %d", res);
res = funman(mul, i, j);
printf("\nres is : %d", res);
// res = funman(add3, i, j); can not be called
printf("\n");
return 0;
}
int funman(int (*ptofun) (int x, int y), int x, int y)
{
return (*ptofun)(x, y);
}
int add(int x, int y)
{
return x + y;
}
int add3(int x, int y, int z)
{
return x + y + z;
}
int mul(int x, int y)
{
return x * y;
}
At this moment you may feel that is there any such scenario where functions need to be passed as parameters in another function. Apparently, you may feel so, but in complex real-time application development, this technique is very important to optimize and reuse the code. Moreover, the code needs to be written in such a way that new functions can be added to it with very few changes. We will discuss it in detail in Design Patterns.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.