... if youve searcher with google you should have come across
www.function-pointer.org
anyway: YES!!! function pointers are VERY useful.
for example when some function requires some cost-function.
Code:
int some_algorithm( struct State, (*pfn_cost)(int, int)) {
if(pfn_cost(blah1, blah2) < pfn_cos(blah1, blah2) {
...
}
...
}
if you have different cost functions you just have to pass a cost function to this - instead of writing multiple versions of your algorithm.
also: you can map values to function
a byte code interpreter might use this mapping - depending on the byte value the appropriate action is performed.
(note that a switch statement would be faster but uglier here - as long as the compiler creates a jump table)
Code:
void f1() {
printf("hi, im function 1\n");
}
void f2() {
printf("hi, im function 2\n");
}
void (*(a_pfn_my_map[2]))();
a_pfn_my_map[0] = &f1;
a_pfn_my_map[1] = &f2;
int i = blah;
if(i >= 0 && i <= 2)
a_pfn_my_map[i]();
another useful thing about function pointers is that you might have function which all do the same - but the implementation differs.
for example matrix multiplication can be done using the ordinary instruction set, or 3dnow or mmx extension or whatever.
consider that:
Code:
if(true == mmx_support)
matrix_mult_mmx(...);
else if(true == 3dnow_support)
matrix_mult_3dnow(...);
else
matrix_mult_fallback(...);
your code would have hundrets of conditionals whenever youd call matrix multiply
instead try this:
Code:
Matrix (*pfn_matrix_multiply)(Matrix *p_m1, Matrix *p_m2);
if(true == mmx_support)
pfn_matrix_multiply = &matrix_mult_mmx;
else if(true == 3dnow_support)
pfn_matrix_multiply = &matrix_mult_3dnow;
else
pfn_matrix_multiply = matrix_mult_fallback;
// now we can always use the fastest implementation without having to worry which implementation actually "hides" behind the pointer
pfn_matrix_multiply(...);
is it clearer now?