Function ptr usage

Started by
6 comments, last by invader 22 years, 2 months ago
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 ?
Welcome to the digital world
Advertisement
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...
I know that I don't know nothing... Operation Ivy
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...
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.)
Nice example Sidshaw
I know that I don't know nothing... Operation Ivy
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 .
Thank you all for helping out.. ^^

what does the following line imply?
From sideshaw said:

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 (…)?
Welcome to the digital world
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.

This topic is closed to new replies.

Advertisement