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?
int (*cmpFn)(void*, void*)is a function pointer — a pointer to a function that can be called later. When you call iSearch you pass it a function that takes twovoid*and returns anint, and it binds that to the parametercmpFn. TheniSearchcan do something likeint x = cmpFn(voidPtr1, voidPtr2);to call that function, passing itvoidPtr1andvoidPtr2as its arguments and storing the return value inxYou can try a simple example by just declaring a function pointer and using it in the same function:
It fails if you declare
int *barbecause that’s not a function pointer, it’s just a pointer to an integer. The syntax for function pointers isrtn_type (*name)(param1_type, param2_type, ...)