Page 1 of 1

Function pointers...

Posted: Sun Jul 19, 2009 10:33 pm
by Shane
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

Re: Function pointers...

Posted: Tue Jul 21, 2009 3:00 pm
by Neo
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.

Re: Function pointers...

Posted: Fri Jul 31, 2009 3:47 pm
by Shane
Comprehensive explanation. Worth a donation :mrgreen: