in Code

Reference: Passing functions as parameters in C

[c]
#include <stdio.h>
//Example to show how to pass
//functions as parameters in C.

//simple function that returns the sum of two ints
int sum(int i, int j) {
return i+j;
}

//simple function that prints a char*
void printSomething(char* something) {
printf("%sn",something);
}

//function that takes
// 2 ints
// 1 char*
// one function that returns an int and takes two ints
// one function that takes a char* returns nothing
void functionThatTakesOtherFunctions(int a,
int b,
char* name,
int (functionA) (int,int),
void (functionB) (char*)) {
printf("Function A: %dn",functionA(a,b));
functionB(name);
}

int main(void) {
//we pass the first two functions as parameters
functionThatTakesOtherFunctions(3,4,
"John Doe",
sum,
printSomething);
return 0;
}
[/c]

This worked fine on my gcc compiler (MacOSX 10.5), no need to even use * or & operators when defining the parameters or when passing the functions as parameters.

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.