Skip to content

How do you pass a function as a parameter in C?

An answer to this question on Stack Overflow.

Question

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?

Answer

Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,

std::function<bool (int)>

where bool is the return type here of a one-argument function whose first argument is of type int.

I have included an example program below:

// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
  return func(a,b);
}
double Add(double a, double b){
  return a+b;
}
double Mult(double a, double b){
  return a*b;
}
int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}

Sometimes, though, it is more convenient to use a template function:

// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
  return func(a,b);
}
double Add(double a, double b){
  return a+b;
}
double Mult(double a, double b){
  return a*b;
}
int main(){
  Combiner(12,13,Add);
  Combiner(12,13,Mult);
}