Manfred
Manfred

Reputation: 159

How to pass a function as a parameter?

How is it possible to give a function (B) a function (A) as a parameter?

So that I can use function A in the function B.

Like the Variable B in the following example:

foo(int B) { ... }

Upvotes: 2

Views: 118

Answers (3)

unwind
unwind

Reputation: 399703

By using function pointers. Look at the qsort() standard library function, for instance.

Example:

#include <stdlib.h>

int op_add(int a, int b)
{
  return a + b;
}

int operate(int a, int b, int (*op)(int, int))
{
  return op(a, b);
}

int main(void)
{
  printf("12 + 4 is %d\n", operate(12, 4, op_add));

  return EXIT_SUCCESS;
}

Will print 12 + 4 is 16.

The operation is given as a pointer to a function, which is called from within the operate() function.

Upvotes: 4

felix021
felix021

Reputation: 2018

write function pointer type in another function's parameter list looks a little weird, especially when the pointer is complicated, so typedef is recommended.

EXAMPLE

#include <stdio.h>

typedef int func(int a, int b);

int add(int a, int b) { return a + b; }

int operate(int a, int b, func op)
{
    return op(a, b);
}

int main()
{
    printf("%d\n", operate(3, 4, add));
    return 0;
}

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

Lets say you have a function you want to call:

void foo() { ... }

And you want to call it from bar:

void bar(void (*fun)())
{
    /* Call the function */
    fun();
}

Then bar can be called like this:

bar(foo);

Upvotes: 2

Related Questions