Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback with parameters

Tags:

c

callback

Im trying to figure out how to use callbacks with parameters in C. The following isnt working. What is the best way to archieve it? (passing arguments for the callback function)

#include <stdio.h>

void caller(int (*cc)(int a)) {
    cc(a);
}

int blub(int a) {
    printf("%i", a); 
    return 1;
}

int main(int argc, char** argv)
{
    caller(blub(5));
    return 1;
}
like image 565
pluckyDuck Avatar asked Oct 10 '11 19:10

pluckyDuck


People also ask

Can callbacks have parameters?

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

How do you pass parameters in callback function in react?

Passing the event object of react as the second argument. If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

What is a callback argument?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


1 Answers

You are doing the call before passing the function, not passing the callback function itself. Try this:

#include <stdio.h>

void caller(int (*cc)(int ),int a) {
    cc(a);
}

int blub(int a) {
    printf("%i", a); 
    return 1;
}

int main(int argc, char** argv)
{
    caller(blub, 1000);
    return 1;
}
like image 189
ArtoAle Avatar answered Oct 11 '22 12:10

ArtoAle