Function Pointers, whats the point????

Started by
5 comments, last by giant 22 years ago
Hi. I bought Tricks of the Game programming Guru''s, and have read and enjoyed most of it. In one of his notes, La Mothe suggests using Function Pointers. I had never heard of or used these, so I decided to give them a shot. I got them working pretty easy, but then asked, what the hell is the point. They dont make the code any easier or shorter, so why use them

int Add( int iOp1, int iOp2 ) { return (iOp1+iOp2); }
int Sub( int iOp1, int iOp2 ) { return (iOp1-iOp2); }

int main()
{
	int (*Math)(int,int);
	int iRetVal;

	Math = Add;
	iRetVal = Math(1,4);
	cout < < "\nAfter 1 + 4, the result is "< < iRetVal;

	Math = Sub;
	iRetVal = Math(5,2); 
	cout < < "\nAfter 5 - 2, the result is "< < iRetVal;

	return 0;
}
 
This works fine, buy why would you bother doing it, it makes the code more difficult and longer. I am sure that there is some cool way that Function Pointers can be used, so if you can please tell me. Thanks Giant "Only two things are infinite, the universe and human stupidity, and I''m not sure about the former." --Albert Einstein
Advertisement
For some strange reason, programming writers seem to introduce language features with the most useless and irrelevant examples (like the classic "Animal" hierarchy for inheritance).

Using a function pointer means you can change which function exactly gets called at runtime (with the restriction that all options must have the same signature), which can be very cool. I use a map of message IDs to function pointers to dynamically respond to windows messages. This allows me to write application-specific message handlers without having to derive new classes from a CWnd or CWindow - unlike MFC and WTL. I simply call RegisterMessageHandler( WM_PAINT, OnPaint ); and I''m done.
There are lots of times when function pointers are useful. The example given by Lamothe is just to show you how it works, rather than an example of how they are useful.

For example, off the shelf sorting algorithms which operate on unknown data types (such as the C qsort() function) take a pointer to a function which compares two data elements.

Also, a common way I''ve seen people implement user definable keys in a game is to define an array of 256 function pointers. If a key, say ''j'' is defined as ''Jump'', then a pointer to the games ''jump'' function is stored in the location 106 of the array. Then whenever a key is pressed, the input controller can simply lookup the key and call whatever function is stored at the appropriate location.

It is also pretty hard to avoid function pointers when using functions kept within dynamically linked dlls. GetProcAddress() gets you a pointer to a function - you have to cast it to the correct function pointer type and then assign it to a function pointer. You can then use it as a normal function from then on.

There are more ways in which function pointers are useful, but I can''t be arsed to go into them.
In the example you''ve given, there is absolutely no reason to use function pointers.

Function pointers are useful when you want to declare a "callback". What that means is that you call a piece of code, and pass it a pointer to a function of your own design. The code then stores that pointer, and is able to call your function when some specified event occurs.

Let''s suppose you have a GUI library which lets you add widgets onto a user interface and display that user interface. One of those widgets is a button, and you want the button to do something when the user clicks on it. However, the designers of the GUI didn''t know what you would want the button to do - there are hundreds of possibilities, and they can''t incorporate code for all of them. So, the answer is to allow you to specify what the button will do yourself. One way of allowing that would be for you to pass a function pointer to the button, so that it can callback to your function whenever someone presses the button.

Note that there are other, arguably cleaner, mechanisms in C++ that allow you to do things like this, so you don''t need to use function pointers very often, if ever.

[C++ FAQ Lite | ACCU | Boost | Learning C++]
probably the most used is when dealing with DLLs that are loaded dynamicly for plugins. in fact some plugin sdks have you return a pointer to (or fill) a struct with function callbacks. in this way you can even only partially fill the struct, and the app can use the default callback without you having to compile it into every plugin. furthermore, the app could give you the default callbacks and you can override them, but still call the function after (or before) your done in case you are only slightly modifing what the function does (for instance printing the args or outcome for debugging).
I''ve used them for AI and player action code
The player has a function pointer that is run each frame i.e.

  // set the 1st action pointerPlayer->pfnAction = Wait;void Wait(){int Response = CheckSurroundings();switch (response){case SPOTENEMY:Player->pfnAction = AnalyzeEnemy;break;case SPOTTREASURE:Player->pfnAction = SearchNLoot.....}AnalyzeEnemy(){ExamineAllVisibleEnemies();ChooseWeapon();bool bEnemyAvailable = ChooseOneEnemy();if (bEnemyAvailable) Player->pfnAction = MoveToEngage;else Player->pfnAction = Wait;}// in the next game loopMoveToEngage(){if (bPathGenerated) {if (!NextToEnemy()) MoveOne();{bPathGenerated = GeneratePath();}if(NextToEnemy()) Player->pfnAction = Strike;}  


It''s intricate but interesting

ZoomBoy
Developing a iso-tile 2D RPG with skills, weapons, and adventure. See my old Hex-Tile RPG GAME, character editor, diary, 3D Art resources at Check out my web-site
yes, a good use for function pointers is to model modes. normally, one might do a switch on a mode variable to determine what to do. you could just set a pointer to a mode and call the mode pointer.
This is a general example but you should get the idea.

  enum MODES{ MODE1, MODE2, MODE3};class CModel{public:	void setMode(int mode)	{		switch(mode)		{		case MODE1: pMode = mode1; break;		case MODE2: pMode = mode2; break;		case MODE3: pMode = mode3; break;		}	}	void act()	{		(this->*pMode)();			}private:	void (CModel::*pMode)();	void mode1(){ cout << "mode1";}	void mode2(){ cout << "mode2";}	void mode3(){ cout << "mode3";}};//CModel  


In C++, explicit function pointers are pretty rare. you can often use virtual functions and polymorphism in their place.

though, in C, i imagine that they are invaluable.

This topic is closed to new replies.

Advertisement