We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now


Function to pointer?

Haho2 asked
Medium Priority
Last Modified: 2010-05-18
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 (...)
  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!

David Chong
Watch Question

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.


   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???



Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
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).


Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.