Function pointers...

C, C++, Visual C++, C++.Net Topics
Post Reply
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Function pointers...

Post by Shane » Sun Jul 19, 2009 10:33 pm

I have a series of functions with same prototype and those are called from a switch/case at the moment.
I was asked to replace this with function pointers. The idea is to speed up the call.

Any help is greatly appreciated.

Shane
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Re: Function pointers...

Post by Neo » Tue Jul 21, 2009 3:00 pm

First you need to define a type for the function prototype.
For example:

Code: Select all

typedef void (*myFuncType) ();
The above function type defines a void function with no parameters.
Ex:

Code: Select all

void myFunction1()
{
}
Now you need to define the function array as below.

Code: Select all

/* Function pointer array */
const myFuncType myFuncArray[NUMBER_OF_FUNCTIONS] = {

	myFunction0,
	myFunction1,
	myFunction2,
	myFunction3,
	myFunction4,
	.....
	.....
	myFunctionn
};
You can call the functions as below by given index.

Code: Select all

myFuncArray[3]();     // this will call 'myFunction3'
Hope this will help.
User avatar
Shane
Captain
Captain
Posts: 226
Joined: Sun Jul 19, 2009 9:59 pm
Location: Jönköping, Sweden

Re: Function pointers...

Post by Shane » Fri Jul 31, 2009 3:47 pm

Comprehensive explanation. Worth a donation :mrgreen:
Post Reply

Return to “C/C++ Programming”