2

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.

6
  • 1
    Yes, but it requires accepting and passing pointers to functions. :( Commented Jan 26, 2013 at 22:08
  • Why is that bad? Could you please elaborate a little bit more? Commented Jan 26, 2013 at 22:09
  • 2
    It's not bad. It's ugly and hard to read compared with Javascript. Commented Jan 26, 2013 at 22:10
  • 1
    @Gaurav Meh. It's only hard to read if you're not comfortable with reasonable C usage. IMO callbacks are callbacks; and it's a pretty minor syntactical difference. Commented Jan 26, 2013 at 22:13
  • 1
    This is a new feature in C++11 called lambdas, unlikely to appear in C. You might find compound statements in GCC an alternative. Commented Jan 26, 2013 at 22:39

2 Answers 2

2

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

Comments

0

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).

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.