Translate

Reference: Passing functions as parameters in 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("%s\n",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: %d\n",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;
}

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.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Leave a Reply