Originally Posted by
Kittu20
Could you please provide some clarity on why and when function pointers are commonly used ?
I'd appreciate any examples you could offer to help me grasp their usefulness ?
I wrote my "entertainment system" in C as a way to relax. It has been morphing over the past 12 years. My "entertainment system" can offer me TV Shows, Movies, Games, Images and Music. In all instances, which ever main selection I choose (Music, Games...), goes to my menu display. My menu display shows the possible values for each of the main headings. Once I choose a value, it executes the function pointer associated with the main heading.
The reason is because my menu display is stupid, it doesn't care what it is displaying, or where is goes after selection. So I can use one smaller function to display the various types, and not need to constantly test where to go after selection. Because mpg123 doesn't know how to show an image file file and vlc doesn't know how to play a game file.
It really makes for cleaner code. And for the record, it was something I had to go back and add, as it wasn't that obvious in the beginning when my "entertainment system" only consisted of 'Movies' and 'Music'.
Code:
typedef struct _menu_item
{
int type;
char path[PATH_SIZE + 1];
char name[NAME_SIZE + 1];
void (*functionPtr) (struct _menu_item *, int);
} MENU_ITEM;