36

Possible Duplicate:
What is the point of function pointers?

I am trying to understand where in the practical scenarios function pointers are used. and also can anyone please give me a practical example where we have to pass function itself as an argument to another function.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
haris
  • 2,003
  • 4
  • 25
  • 24
  • This is C#, but it also goes into C/C++ and the practicality of function pointers: http://stackoverflow.com/questions/667410/the-benefits-of-using-function-pointers – Algorhythm Jan 23 '12 at 16:48

8 Answers8

43

Function pointers can be useful when you want to create callback mechanism, and need to pass address of a function to another function.

They can also be useful when you want to store an array of functions, to call dynamically for example.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
17

Callback routines appear to be the most common scenario put forth thus far. However, there are many others ...

Finite State Machines where the elements of (multi-dimensional) arrays indicate the routine that processes/handles the next state. This keeps the definition of the FSM in one place (the array).

Enabling features and disabling of features can be done using function pointers. You may have features that you wish to enable or disable that do similar yet distinct things. Instead of populating and cluttering your code with if-else constructs testing variables, you can code it so that it uses a function pointer, and then you can enable/disable features by changing/assigning the function pointer. If you add new variants, you don't have to track down all your if-else or switch cases (and risk missing one); instead you just update your function pointer to enable the new feature, or disable the old one.

Reducing code clutter I touched upon this in the previous example. Examples such as ...

switch (a) {
case 0:
    func0();
    break;
case 1:
    func1();
    break;
case 2:
    func2();
    break;
case 3:
    func3();
    break;
default:
    funcX();
    break;
}

Can be simplified to ...

/* This declaration may be off a little, but I am after the essence of the idea */
void (*funcArray)(void)[] = {func0, func1, func2, func3, funcX};
... appropriate bounds checking on 'a' ...
funcArray[a]();

There are many more. Hope this helps.

Sparky
  • 13,505
  • 4
  • 26
  • 27
  • 3
    FWIW, the declaration should be `void (*funcArray[])(void) = {func0, func1, func2...};` (`funcArray` is an array of pointers to functions...). Remember declaration mimics use; if the expression in the code is `funcArray[a]()`, then the declaration is going to be structured the same way. – John Bode Jan 23 '12 at 18:28
  • 1
    @JohnBode - Much appreciated. Though I've been working with C for over 20 years, I still get mixed up on function pointer syntax. Usually I opt for the easier (for me) route of typedef'ing the function pointer first and then declaring an array of the typedef'ed variable. – Sparky Jan 23 '12 at 18:54
  • @Sparky Agreed regarding the typedef. It makes situations like arrays of function pointers or pointers to function pointers much easier to read. – Brian McFarland Jan 23 '12 at 22:50
  • 1
    @Sparky: I have to disagree about the typedefs; for me, they obscure as much as they illuminate. If I have a slightly ugly type like `int *(*(*f)[N])(void)`, I know immediately that expressions involving `f` look like `x = *(*(*f)[i])();` - I don't have to search for a series of typedefs and reconstruct the expression from that. – John Bode Jan 25 '12 at 11:52
12

One common use is to implement a callback function.

Try to sort something by using qsort library function. It's last parameter is a pointer to the comparator function written by you.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
10

The first thing that comes to my mind as a very useful application is a button. Take the following code:

int buttonID = CreateButton ("Click Me!", 100, 100, 200, 100, onClick);

This would create a button at (100,100) with width 200 and height 100. Every time you click it, onClick is called.

I use something similar in a personal Windows API wrapper. It makes creating buttons etc so much easier.

chris
  • 60,560
  • 13
  • 143
  • 205
  • After half an hour of reading about function pointers, this example made it all ... ehm, "click". Very neat accessible example of where function pointers can be useful. – aulven Sep 12 '22 at 18:50
6

There are two major uses for function pointers:

  • callbacks - used for event handlers, parser specialization, comparator function passing...
  • plugins and extensions - the pointers to functions provided by plugins or library extensions are gatherd by a standard functio GetProcAddress, dlsym or similar, which take the function identifier as name and return a function pointer. Absolutely vital for APIs like OpenGL.
datenwolf
  • 159,371
  • 13
  • 185
  • 298
5

In MOST cases, it's essentially the C way of doing dependency inversion. The wiki article states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions.

The classic example ofqsort does this in the sense that the higher-level sort function does not depend on the type, size, or comparison method of the data to be sorted. So if you qsort() an array of ints, the details are sizeof(int) and your compare implementation. The abstraction is an array of arbitrarily sized elements and a function that compares elements of that type.

See also: Inversion of Control.

I'm surprised no one has mentioned pthread_create() as an example.

The only common use I can think of that cannot be generalized as dependency inversion is implementing switch-like flow control on non-switchable data types. For example, if you've ever wanted to switch on a string, create arrays mapping sorted string keys to function pointers and do a binary search. It's not O(1) like a switch, but better than blindly doing strcmp()'s in a big if-else until you find a match. But maybe not any better than tokenizing the string and using an actual switch.

Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
3

Well, the #1 stock answer is: qsort. The comparator routine that qsort will use is passed as a function pointer. A lot of other “generic algorithm” functions will take comparators in similar ways; e.g. perhaps a hashtable implementation might accept your hash function.

C-language GUI toolkits and application frameworks (e.g. Gnome/Gtk+/Glib) often accept function pointers as “callbacks” for timer or user interface events. (EG: “call this function whenever this button is clicked” or “…whenever this timer expires”)

In fact, most “OOP-like” or “event-driven” code in C will accept function pointers for a similar reason.

BRPocock
  • 13,638
  • 3
  • 31
  • 50
3

You can use it to pass a callback to a function. For instance, you might want to sort an array using qsort(). This function takes a comparison function as one of its arguments, which means that you can use your own sorting orders:

// All odd numbers are before even numbers
int cmpoddeven(const void *xp, const void *yp) {
  int x = *((int*) xp);
  int y = *((int*) yp);
  if(x == y)
    return 0;
  if(x % 2 == y % 2) {
    return (x < y ? -1 : 1);
  if(x % 2 == 1)
    return -1;
  return 1;
}

int main() {
   int array[] = {1, 2, 3, 4, 5};
   // calling qsort with cmpoddeven as the comparison function
   qsort(array, 5, sizeof(int), &cmpoddeven);
   // array == {1, 3, 5, 2, 4};
}
Frxstrem
  • 38,761
  • 9
  • 79
  • 119
  • One common usage of function pointers in C is found in embedded software for handling interrupts. The interrupt handler needs to call a specific function for any given interrupt. This involves programming the interrupt controller with the address of that function. – Phil Jun 13 '19 at 02:58