0

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?

0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I know they are equally fine, I only think ptr(b) is more readable, I wanted to show that. But you are right, it is pointless because it's correct anyway. I'll remove that part as it may confuse more than it helps. Thanks for the feedback.

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.