Link to home
Start Free TrialLog in
Avatar of Haho2
Haho2

asked on

Function to pointer?

Hi, I am trying to improve my knowledge of C.
I would like to know what is the difference between
a function declared as :
  1)  eg.   void MyFunction (...)
and
  2)  eg.   void *Myfunction (...)
I know 2) is a pointer to a funciton but when would I want to use 1) or 2) and why??? a simple example would be great!
Thanks!!!!

David Chong
Avatar of braveheart
braveheart

I am sure you know when you would use 1) but a pointer to a function is useful where you wish to call different functions according to the data that you wish to process.

For instance, you may wish to use different functions to draw the outline of a shape or to draw a filled shape, according to some shading mode that has been set earlier in the program.  Of course you could always test which mode you are in before calling the function but you would have to do this wherever it is called.  

You could move the test inside some wrapper function or macro but a more elegant solution would be to set the value of the function pointer appropriately when the mode is first set and then invoke the drawing function via the pointer when it is wanted. Such a  function is often known as a callback.

Of course, you might want to add more modes, so you would have to extend the test to a switch statement if you were not using the callback approach.

Even more fundamentally, if you are writing a library for use by someone else, you cannot foresee all the possible ways in which the library may be used and you want to make it easy to extend. This is achieved more easily by allowing users to define their own callbacks than by trying to predict what they may want to do.
Avatar of Haho2

ASKER

Thanks,
   but I have seen sample code from C books that uses 2) but it is not used for a callback function purposes..it is just a usual function with a pointer to it... is there any other reasons???

Bye!

David

ASKER CERTIFIED SOLUTION
Avatar of xyu
xyu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Parsers often make use of the "pointer to function" mechanism so that switch statements don't grow too big. For instance, to keep track of the pointers you only need an array or two, rather than hardcoding a switch statement.
braveheart it was just a sample.. :)
xyu, my remark was not a comment on your example but a response to Haho2's subsequent question "is there any other reasons???" (sic).
Avatar of Haho2

ASKER

thanks!