Alex Rivera | Logout

The Benefits of Using Function Pointers

Asked 2009-03-20T18:38:19.277
17

I have been programming for a few years now and have used function pointers in certain cases. What I would like to know is when is it appropriate or not to use them for performance reasons and I mean in the context of games, not business software.

Function pointers are fast, John Carmack used them to the extent of abuse in the Quake and Doom source code and because he is a genius :)

I would like to use function pointers more but I want to use them where they are most appropriate.

These days what are the best and most practical uses of function pointers in modern c-style languages such as C, C++, C# and Java, etc?

Edit
Report

1 Answer

3

Function pointers are a poor man's attempt to be functional. You could even make an argument that having function pointers makes a language functional, since you can write higher order functions with them.

Without closures and easy syntax, they're sorta gross. So you tend to use them far less than desireable. Mainly for "callback" functions.

Sometimes, OO design works around using functions by instead creating a whole interface type to pass in the function needed.

C# has closures, so function pointers (which actually store an object so it's not just a raw function, but typed state too) are vastly more usable there.

Edit One of the comments said there should be a demonstration of higher order functions with function pointers. Any function taking a callback function is a higher order function. Like, say, EnumWindows:

BOOL EnumWindows(          
    WNDENUMPROC lpEnumFunc,
    LPARAM lParam
);

First parameter is the function to pass in, easy enough. But since there are no closures in C, we get this lovely second parameter: "Specifies an application-defined value to be passed to the callback function." That app-defined value allows you to manually pass around untyped state to compensate for lack of closures.

The .NET framework is also filled with similar designs. For instance, IAsyncResult.AsyncState: "Gets a user-defined object that qualifies or contains information about an asynchronous operation." Since the IAR is all you get on your callback, without closures, you need a way to shove some data into the async op so you can cast it out later.

answered 2009-03-20T22:17:24.990

Your Answer