piggyback
piggyback

Reputation: 9254

Javascript callback coding style in C?

Ok this question may be shocking for javascript haters and hard-core developers, forgive me!

I love the way I can write a callback function in javascript

var on = function(isTrue, doThis) {if (isTrue) doThis();}

Is there any possibility to replicate the same idea in C ? I know it's type dependent. More and less this is my case:

I have multiple booleans and multiple filters so my use would be, instead of writing

if (thisIs == true) executeThisVoid(passingThisStruct)

I would love to write:

on(thisIs, function(struct){ do this and this})

or simply

on(thisIs, executeThisVoid);

Many thanks everybody.

Upvotes: 2

Views: 109

Answers (2)

Gaurav
Gaurav

Reputation: 12796

OK, here goes. First define on:

void on(int thisIs, void (*executeThis)(void)) {
    if (thisIs)
        (*executeThis)();
}

Then, define someVoid:

void someVoid(void) {
    /* ... */
}

Then, within another function, call on:

on(1, someVoid);

Upvotes: 2

Chen Kinnrot
Chen Kinnrot

Reputation: 21015

As I know, in C you can point to functions... so, If on is a method that get two function pointers, and thisIs is a function pointer, and executeThisVoid is alos one, you should not have any problems, just need to hold the struct in an outer scope, or create another struct that will represents a chain of method calling(to hold parameters and other stuff).

Upvotes: 0

Related Questions