I guess using a function pointer inside a struct has something to do with encapsulating a function within a structure...? If so, then how exactly is this achieved??
And what good does it bring to have a function pointer inside a struct rather than simply defining the function?
Assume the function takes 2 variables and calls 4 different functions. Let there be a structure as follows:
It would be easy to compare the input values against the structure values and call corresponding function.
It might seem it is better to use if..else... But think of cases in which there are more than 100 such cases to be checked
the benifit of having function pointer defined in the structure, is related to the code design. the goal is to get your code more structured.
Defining variables and functions in a structure is like defining class in oriented object languages
Refer to the following link for more details
function pointers inside structures are the base of object-programming in C (see http://www.planetpdf.com/codecuts/pdfs/ooc.pdf ). It is really really for medium-to-large C projects.
An example:
Header:
Source:
Having function pointer inside struct will be useful for certain data structures such as binary search tree.
Lets say , i want to insert an element whose struct is
into a binary search tree. but i would like the BST to use my function to compare the elements while storing and searching.
and the bst struct will be as follows.
Now, i will use the BST as follows.
The advantage i see is i don't need to keep on pass this function pointer into my all BST operation functions .
but storing all public functions inside struct will bring the OOP style inside C code , like what others says.