Archived

This topic is now archived and is closed to further replies.

invader

Function ptr usage

Recommended Posts

I learned function pointer for ages, and I have not yet discover a useful place where I can apply them in window programming( apart from winproc ) || general c/c++ programming under what circumstances should we apply function pointers ?

Share this post


Link to post
Share on other sites
Let say you have a frequently used algorithm that have 2 or more way to be solved according to a situation. You will certainly have "funcA", "funcB" and so on (as many as there are ways to do it). Instead of selecting the right function by test during execution (switch...), you should use a function pointer that point to the right one and that is generically called (let''s say "func").

I hope it''ll help you...

Share this post


Link to post
Share on other sites
A good example would be a puzzle game with different difficulty levels. Say one level was gonna use a brute force method, one a depth search, one a priority table, etc. You''d just implement each one in a function, stick them in an array of function pointers and then make your call something like this:

gameAIRoutine[gameCurrentDifficultyLevel]( ... );

Really easy to implement difficulty levels this way and it keeps the code looking nice and clean. Bonus...

Share this post


Link to post
Share on other sites
qsort() takes a pointer to a compare-function and lets you decide how to sort the elements. (If you''re using C++ however, then it''s probably best to use std::sort() and a functor, because of inlining.)

Share this post


Link to post
Share on other sites
Function pointers used to get a bit more use in C, because it doesn''t support polymorphism as a language construct. You could use function pointers to build a vtable by hand if you needed polymorphic behavior. Now we just use virtuals .

Share this post


Link to post
Share on other sites
Thank you all for helping out.. ^^

what does the following line imply?
[Quote From sideshaw]
gameAIRoutine[gameCurrentDifficultyLevel]( ... );
quote:


are there better ways to retrieve function ptr..?
(isn''t this just like how we retrieve 2D array? )
why do we use (...)?

Share this post


Link to post
Share on other sites
It was psuedo-code, not actual code.
The name implied that gameAIRoutine is an array of function pointers, gameCurrentDifficultyLevel is an integer describing the current difficulty level, and the "..." would be replaced by arguments to the function to be called.

Share this post


Link to post
Share on other sites