Pointer is a variable which holds the address of another variable. Where, function pointer is again a variable which holds the address of a function.
If you think pointers are evil, then function pointers must be Satan for you. 🙂 Well, is there any easy way to create function pointers from function prototype? Indeed, there is. Its the “BAT” technique. Never heard about it before? No problem. Its invented by me just now. After watching BatMan series from cartoon network.
The “BAT” technique is this –
- Put Bracket or parenthesis around the function name.
- Add Asterisk or star in-front of function name.
- Now Typedef it to create a new datatype. Means change the function name to new datatype name and add typedef infront of it.
- Now you can use the new function pointer datatype like ordinary variables.
For instance, Assume we want to make a function pointer for function – DWORD MyFunction( int a, int b).
DWORD (MyFunction)( int a, int b);
DWORD (*MyFunction)( int a, int b);
typedef DWORD (*MyFunctionPtr)( int a, int b);
Ah! you have created a function pointer – MyFunctionPtr for function type – ‘DWORD MyFunction( int a, int b)’
Now you can use it like any other variable in your code. For instance, just see the following code snippet with real world usage of function pointers.
// Callback function for progress notification.
bool NotifyProgress( int Percentage )
// Display progress and return true to continue.
// typedef function pointer.
typedef bool (*NotifyProgressPtr)( int Percentage );
// DVD Burning function with pointer to NotifyProgress
// to update progress.
void BurnDVD( NotifyProgressPtr FnPtr )
for( int Progress = 0; Progress <= 100; ++Progress )
// Call the function.
// Main function.
int _tmain(int argc, _TCHAR* argv)
// Ummm... Burn one DVD.
BurnDVD( NotifyProgress );
Function pointers are not that much evil. Isn’t it? 😉
Targeted Audience – Beginners.