2

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) { ... }
1
  • 2
    function pointer is the thing you're looking for, but be warned: It's a bit messy and in my opinion not suitable for beginners. Commented Sep 13, 2012 at 10:54

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest not using "operator" as a variable name to avoid confusion with actual operators in C++. But of course it is valid C.
@stefan I normally don't care much about keeping my C valid C++, but sure, why not. I renamed the argument, thanks.
2

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;
}

2 Comments

+1: interesting - today I learned something - I never knew that you could use that syntax - I've only ever used explicit function pointers, e.g. typedef int (*func)(int a, int b);
yeah. that is designed to simply the usage of function pointer.
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.