812

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?

9
  • 17
    If you're using functions/arrays as variables, ALWAYS use typedef. Jan 13, 2014 at 21:09
  • 8
    We call it Function pointer
    – AminM
    Apr 1, 2014 at 11:11
  • 10
    @MooingDuck I don't agree with your suggestion, and your suggestion lacks reasoning to support the conclusion. I personally prefer never using typedef on function pointers, and I think it makes the code clearer and easier to read.
    – andrewrk
    Dec 16, 2015 at 22:26
  • 3
    @andrewrk: You prefer void funcA(void(*funcB)(int)) and void (*funcA())() to typedef void funcB(); void funcA(funcB) and funcB funcA()? I dont see the upside. Dec 16, 2015 at 23:27
  • 3
    @MooingDuck not disagreeing with either of you, but the upside to me is that you know exactly what's going on at a glance, rather than relying on the programmer having chosen a reasonable name like "funcA", and having to scroll through code files twice to figure out what that variable is for. Having said that, if you have good coding style I can see it working nicely. But then again, if you have good coding style, I can see the explicit version not being a problem either. I have a feeling your style of writing the explicit version above was somewhat intentionally 'dense' to make your point. :) Oct 10, 2021 at 8:48

10 Answers 10

964

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Source

17
  • 63
    In your first and last code examples, the * is not compulsory. Both the function parameter definition and the f function call can take f just as is without *. It might be a good idea to do it as you do though, to make it obvious that parameter f is a function pointer. But it hurts readability quite often.
    – Gauthier
    Feb 22, 2012 at 12:52
  • 6
    See [c99, 6.9.1§14] for examples. Both are correct of course, I just wanted to mention the alternative.
    – Gauthier
    Feb 22, 2012 at 12:58
  • 9
    Really? The top-rated answer doesn't make a single reference to using a typedef for function pointers? Sorry, have to down-vote. Oct 1, 2014 at 8:03
  • 5
    @JonathonReinhart , what would be advantages with 'typedef' apprach? This version looks much cleaner though and lacks extra statements too. pretty much starter here. Feb 22, 2015 at 7:04
  • 6
    @JonathonReinhart well spotted; it should be explicitly noted that pointer typedefs obfuscate the code and therefore should not be used.
    – M.M
    Nov 24, 2015 at 2:39
164

This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

typedef void (*functiontype)();

Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

void dosomething() { }

functiontype func = &dosomething;
func();

For a function that returns an int and takes a char you would do

typedef int (*functiontype2)(char);

and to use it

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

boost::function<int (char a)> functiontype2;

is so much nicer than the above.

3
  • 5
    If you want to "turn a function pointer into a type", you don't need the boost library. Just use typedef; it's simpler and doesn't require any extra libraries.
    – wizzwizz4
    Apr 9, 2016 at 11:50
  • 12
    Isn't boost library C++? Why do you mention it in a C question? Oct 2, 2020 at 12:48
  • 1
    For functions that use a different calling convention, place the calling convention before the first *. Like this: typedef void(__stdcall* funcPtr)(int arg1, int arg2);
    – Dwedit
    Sep 19, 2021 at 18:04
114

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);
}
5
  • 79
    The question is about C; C++ does not apply here.
    – Super Cat
    Oct 29, 2015 at 23:44
  • 19
    The question for C++ (stackoverflow.com/questions/6339970/…) is referred to here, so I think this answer is in place.
    – mr_T
    Mar 24, 2016 at 11:00
  • 15
    Maybe the question for C++ shouldn't be referred to here because this question for is C. Apr 19, 2018 at 16:22
  • 22
    This question came up first when I searched "c++ function call as parameter", so this answer is serving its purpose well here regardless.
    – ufoxDan
    Nov 7, 2019 at 21:50
  • This answer is wrong because C++ isn't C.
    – Marco
    Apr 23 at 14:02
47

Pass address of a function as parameter to another function as shown below

#include <stdio.h>

void print();
void execute(void());

int main()
{
    execute(print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void f()) // receive address of print
{
    f();
}

Also we can pass function as parameter using function pointer

#include <stdio.h>

void print();
void execute(void (*f)());

int main()
{
    execute(&print); // sends address of print
    return 0;
}

void print()
{
    printf("Hello!");
}

void execute(void (*f)()) // receive address of print
{
    f();
}
2
  • 7
    Very nice answer, with whole blocks of code (instead of slicing everything into a incomprehensible mess). Could you elaborate on the differences of both techniques? Jan 29, 2020 at 15:17
  • 2
    Correct me if I'm wrong, AFAIK function names are pointers just like array names so in the first example you are passing function object and compiler does implicit conversion, in the second example you are directly passing function pointer which is explicit conversion.
    – Sekomer
    Jun 27, 2021 at 19:38
20

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));
2
  • What document are you quoting from? Any link to it? Jan 29, 2020 at 21:41
  • 4
    I'm quoting from the ISO C11 standard. Feb 5, 2020 at 12:57
6

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22
1
  • 1
    Please explain the parameter "bool (&cmp)(int a, int b)" Why do you use an ampersand and not a star as is usual in function pointer parameters.
    – Erik
    Jun 4 at 11:37
4

You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.

0
typedef int function();

function *g(function *f)
{
    f();
    return f;
}

int main(void)
{
    function f;

    function *fn = g(f);

    fn();
}

int f() { return 0; }
1
  • 3
    This might be a good solution, but it found itself in the Low Quality Answers queue for review. Please add some discussion explaining the solution and how it works, to make it more helpful to future readers of this site.
    – joanis
    Sep 24, 2021 at 13:49
-1

technically you can not, but there is tricky way to do that, passing pointer pointing to a function as parameter.

-8

It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.

#include <stdio.h>

int IncMultInt(int a, int b)
{
    a++;
    return a * b;
}

int main(int argc, char *argv[])

{
    int a = 5;
    int b = 7;

    printf("%d * %d = %d\n", a, b, IncMultInt(a, b));

    b = 9;

    // Create some local code with it's own local variable
    printf("%d * %d = %d\n", a, b,  ( { int _a = a+1; _a * b; } ) );

    return 0;
}
1
  • You're just invoking a function. How would you pass some other function in place of IncMultInt? Nov 28, 2019 at 5:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.