Function Pointer
In my Apple interview, I was shown this syntax in C++ and was a little rusty with that.
https://stackoverflow.com/questions/2298242/callback-functions-in-c
// Define callback signature.
typedef void (*DoneCallback) (int reason, char *explanation);
// A method that takes a callback as argument.
void doSomeWorkWithCallback(DoneCallback done)
{
...
if (done) {
done(1, "Finished");
}
}
//////
// A callback
void myCallback(int reason, char *explanation)
{
printf("Callback called with reason %d: %s", reason, explanation);
}
/////
// Put them together
doSomeWortkWithCallback(myCallback);
Can you do something like this?
void doSomething(void *f) {
f(5);
}
void g(int x){
x+5;
}
doSomething(g);
NO
void*
is a generic pointer type in C++ that can point to any data type, but it does not retain information about the type of what it points to. Therefore, you cannot callf(5)
sincef
is treated as avoid*
, and the compiler doesn’t know it’s meant to be a function pointer.
If you’re really stupid, you can do this (casting a void*)
- this is done a lot in embedded programming lol
void doSomething(void* f) {
// Cast void* to a function pointer type int(*)(int)
int (*funcPtr)(int) = (int (*)(int))f;
}
, to make it work you need
void doSomething(void (*f)(int)) {
f(5);
}
Note that if g returned an integer, you’d need to do this
void doSomething(int (*f)(int)) {
f(5);
}
int g(int x){
return x+5;
}
doSomething(g);