How to pass a function in a function?

Posted by SoulBeaver on Stack Overflow See other posts from Stack Overflow or by SoulBeaver
Published on 2010-06-10T17:51:40Z Indexed on 2010/06/10 18:02 UTC
Read the original article Hit count: 254

Filed under:
|
|

That's an odd title. I would greatly appreciate it if somebody could clarify what exactly I'm asking because I'm not so sure myself.

I'm watching the Stanford videos on Programming Paradigms(that teacher is awesome) and I'm up to video five when he started doing this:

void *lSearch( void* key, void* base, int elemSize, int n, int (*cmpFn)(void*, void*))

Naturally, I thought to myself, "Oi, I didn't know you could declare a function and define it later!". So I created my own C++ test version.

int foo(int (*bar)(void*, void*));
int bar(void* a, void* b);

int main(int argc, char** argv)
{
    int *func = 0;
    foo(bar);

    cin.get();
    return 0;
}

int foo(int (*bar)(void*, void*))
{
    int c(10), d(15);
    int *a = &c;
    int *b = &d;
    bar(a, b);
    return 0;
}

int bar(void* a, void* b)
{
    cout << "Why hello there." << endl;
    return 0;
}

The question about the code is this: it fails if I declare function int *bar as a parameter of foo, but not int (*bar). Why!?

Also, the video confuses me in the fact that his lSearch definition

void* lSearch( /*params*/ , int (*cmpFn)(void*, void*)) is calling cmpFn in the definition, but when calling the lSearch function

lSearch( /*params*/, intCmp );

also calls the defined function int intCmp(void* elem1, void* elem2); and I don't get how that works. Why, in lSearch, is the function called cmpFn, but defined as intCmp, which is of type int, not int* and still works? And why does the function in lSearch not have to have defined parameters?

© Stack Overflow or respective owner

Related posts about c++

Related posts about pointers