Void pointer initialization? If not, what is it?
2 answers
In this example, cb is a pointer to a function that takes no arguments and has no return value
for example if i have
void printHello( ) {
cout << "hello" << endl;
}
then later I could
void (*cb)(void);
cb = printHello;
I can call the function using:
cb();
which is called by printHello ();
The utility of this is that I can now assign different functions to cb and call them and pass them to other functions like any other pointer variable.
Often, for clarity, programmers will create a specific type for this to avoid having to write this gulp:
typedef void (*tPrtToVoidFn)(void);
tPtrToVoidFn cb;
cb = printHello;
For comparison, a pointer to a function that returns an int would look like this:
int (*ptrToFunctionReturningInt)(void);
and a pointer to a function that takes an int and returns nothing would look like this:
void (*ptrToFunctionReturningNothing)(int);
+9
source to share