Hi What is the point of using pointers to functions in C ? Why not call directly a function ?
Thanks Elico
yea. whats the point. I say we should ban it. change the standard. its too thick anyway.
Calling functions directly means you need to modify the code with lots of "if (x) fnk1() else if (b) fnk2() .." in some situations.
Like if you have implemented a container class that has a function
iterate_all_elements(my_list)
Iterate over all elements and do what? Create lots of iteration functions:
iterate_all_elements_and_print(my_list); iterate_all_elements_and_save(my_list); iterate_all_elements_and_sum_values(my_list); iterate_all_elements_looking_for_duplicates(my_list); ...
Isn't it better with:
iterate_all_elements(my_list,print_element); iterate_all_elements(my_list,save_element); ...
So you don't need to rewrite your iterate_all_elements() function but instead just supply a new function pointer.
May be you want to be able to call different ones? qsort() ?
"Why not call directly a function ?"
That only works when you know at compile time what function to call!
consider a situation where you have an uart or a keypad from where the user is going to give input commands at runtime. depending upon the commands, the functions will be executed.
under such a case you will have a very big if-else (alternatively switch-case) statement.
if(input_cmd == 0x01) function1(); else if(input_cmd == 0x02) function2(); else if(input_cmd == 0x03) function3(); ... else if(input_cmd == 0xFF) function255(); // The list will be very long, clumsy, unorganized, poor readability
on contrary, consider an array of function
CMDS_Functn FunctionArray1[256] = { /*00-07*/ (*NotDef),(*funtion1),(*function2),(*function3), ... /*F7-FF*/ (*function254), (*function255)}; //functions can be called as Cur_Func = FunctionArray1[input_cmd].Cur_FunctnPtr; //Load current Function Pointer (*Cur_Func)();