3

How can I create a "function pointer" (and (for example) the function has parameters) in C?

1

5 Answers 5

15

http://www.newty.de/fpt/index.html

typedef int (*MathFunc)(int, int);

int Add (int a, int b) {
    printf ("Add %d %d\n", a, b);
    return a + b; }

int Subtract (int a, int b) {
    printf ("Subtract %d %d\n", a, b);
    return a - b; }

int Perform (int a, int b, MathFunc f) {
    return f (a, b); }

int main() {
    printf ("(10 + 2) - 6 = %d\n",
            Perform (Perform(10, 2, Add), 6, Subtract));
    return 0; }
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting example - adding a float and two chars?
Of course, haven't you always wanted to add 3.145 to 'z' and return the result as an integer!? I'll change the example to something a bit saner.
5
    typedef int (*funcptr)(int a, float b);

    funcptr x = some_func;

    int a = 3;
    float b = 4.3;
    x(a, b);

Comments

0

I found this site helpful when I was first diving into function pointers.

http://www.newty.de/fpt/index.html

Comments

0

First declare a function pointer:

typedef int (*Pfunct)(int x, int y);

Almost the same as a function prototype.
But now all you've created is a type of function pointer (with typedef).
So now you create a function pointer of that type:

Pfunct myFunction;
Pfunct myFunction2;

Now assign function addresses to those, and you can use them like they're functions:

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

int subtract(int a, int b){
    return a - b;
}

. . .

myFunction = add;
myFunction2 = subtract;

. . .

int a = 4;
int b = 6;

printf("%d\n", myFunction(a, myFunction2(b, a)));

Function pointers are great fun.

Comments

0

You can also define functions that return pointers to functions:

int (*f(int x))(double y);

f is a function that takes a single int parameter and returns a pointer to a function that takes a double parameter and returns int.

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.