Guest_imported
New member
- Jan 1, 1970
- 0
I need to pass a function as a variable to another function. I have looked everywhere and cannot figure out how to do this. Any help would be much appreciated.
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
/*
Define the type of a function pointer
with prototype.
To understand a type declaration,
just start from the name and expand
respecting 'operator' precedence
which is (from higher to lower):
A) parenthesis surrounding name,
B) parenthesis following name,
array bracket (left to right)
C) pointer before name (right to left)
D) other type before name
Here we have: int (*t_ptrFct)(int, int)
which is
rule/description
(*t_ptrFct) : (A) t_ptrFct is a pointer to ...
(...)(int, int) : (B) ... a function taking 2 ints ...
int (...)(...) : (D) ... and returning an int.
Note that without the parenthesis we would have get:
int *t_ptrFct(int, int)
which is
(B) a function ...
(C) ... returning a pointer to ...
(D) ... an int
*/
typedef int (*t_ptrFct)(int, int);
/*
One arg of the function is of the type just
declared, i.e. a pointer to a function.
*/
int
callWithSquaredArgs(t_ptrFct myPtrFct,
int data1, int data2)
{
/* Call function pointed by myPtrFct
with arguments squared */
(*myPtrFct)(data1*data1, data2*data2);
}
/* A simple minimum function */
int
minFct(int data1, int data2)
{
return (data1 <= data2) ? data1 : data2;
}
/* A simple maximum function */
int
maxFct(int data1, int data2)
{
return (data1 >= data2) ? data1 : data2;
}
/*
To print expression and its value
without duplication so avoiding the
copy-paste-and-forget-to-change-both problem
*/
#define PRINT_EXP_AND_VALUE(EXP, TYPE) printf("%s = "TYPE"\n", #EXP, EXP)
int
main(int argc, char *argv[])
{
/* call max function with args squared */
PRINT_EXP_AND_VALUE
(callWithSquaredArgs(&maxFct, 2, 3), "%d");
/* call min function with args squared */
PRINT_EXP_AND_VALUE
(callWithSquaredArgs(&minFct, 2, 3), "%d");
/*
Note:
The PRINT_EXP_AND_VALUE macro are just for display.
You can of course use callWithSquaredArgs alone.
*/
printf("min squared = %d\n"
"max squared = %d\n",
callWithSquaredArgs(&minFct, 4, 5),
callWithSquaredArgs(&maxFct, 4, 5));
return 0;
}
callWithSquaredArgs(&maxFct, 2, 3) = 9
callWithSquaredArgs(&minFct, 2, 3) = 4
min squared = 16
max squared = 25