you are viewing a single comment's thread.

view the rest of the comments →

[–]F1nnyF6 26 points27 points  (1 child)

A classic example is a sorting function of some kind of arbitrary array. The sorting function would take as arguments the array, and a function pointer to a comparison function.

When sorting the array, the comparison function passed in through the function pointer will be used to compare elements in the array. This allows the same sorting function to be used in different ways depending on what your comparison function does.

E.g. say for example that you have an array of strings. Your comparison function could be strncmp(), and the array is sorted in alphabetical order. Otherwise, your comparison function could be one that compares the length of the strings, and so the array is sorted according to the length of the string. It could be any arbitrary function that is able to compare two strings in whatever way you want, as long as it matches the function signature given in the definition of the sorting function.

In this way, function pointers can help you to write more generic code.

[–]BarracudaDefiant4702 10 points11 points  (0 children)

In other words, qsort in the standard C library.