user3822607
user3822607

Reputation: 69

Passing variables using call back function pointers

I would like to pass variable 'c' from the main to (an arbitrary) function A using callback function B. As indicated, I can pass the variable 'b' to function A within function b, but I cannot find a syntax to pass from main.

#include<stdio.h>

void A(int a)
{
    printf("I am in function A and here's a: %d\n", a);
}

// callback function
void B(void (*ptr)(int b) )
{
//    int b = 5;
    int b;
    printf("I am in function B and b = %d\n", b);
    (*ptr) (b); // callback to A
}

int main()
{   
    int c = 6;
    void (*ptr)(int c) = &A;

    // calling function B and passing
    // address of the function A as argument
    B(ptr);

   return 0;
}

Is there a syntax to pass a variable from main to an arbitrary function using a call back?

Upvotes: 0

Views: 254

Answers (2)

viraptor
viraptor

Reputation: 34145

What may be confusing you is the name of the parameter in function declarations. They're not necessary and it's better to drop them.

These two lines are the same:

void (*ptr)(int c) = &A;
void (*ptr)(int) = &A;

the c in that expression had nothing to do with the variable c. Additionally you can use:

typedef void (*callback_t)(int);

and use the following for declaration instead.

callback_t ptr = &A;

Then it's more obvious you need two parameters for B.

void B(callback_t ptr, int param) {
    ptr(param);
}

int main() {
    ...
    B(ptr, c);
}

Upvotes: 2

Pablo
Pablo

Reputation: 13570

Calling the function pointer with (*ptr) (b) is OK, but I prefer to call it ptr(b), for me that's more readable. That's just my preference.

If you want to pass the variable to the callback from main, then change B to accept a value for the callback and use that variable when calling the callback with the function pointer, like this:

void B(void (*ptr)(int b), int var_for_callback)
{
    printf("I am in function B and var_for_callback is %d\n", var_for_callback);
    ptr(var_for_callback);
}


int main()
{   
    int c = 6;
    void (*ptr)(int c) = &A;

    // calling function B and passing
    // address of the function A as argument
    B(ptr, c);

   return 0;
}

Now you pass the value of c to B and B passes that to the callback passed in ptr.

Upvotes: 1

Related Questions