This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

POINERS TO FUNCTIONS

Hi
What is the point of using pointers to functions in C ?
Why not call directly a function ?

Thanks
Elico

Parents
  • 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.

Reply
  • 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.

Children
No data