2

What are some practical examples and application of using a pointer to a function? I don't grasp why someone would need to use it.

Thanks

Definity
  • 691
  • 2
  • 11
  • 31

3 Answers3

4

Two principal reasons:

1) you can pick which function to use in certain situations.

2) you can provide a callback function to another function (e.g the C standard library function qsort takes a function pointer as a parameter: you write this function yourself to tell qsort about how to compare two values).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

If you have one object that contains another object, (let us label them A and B), you can pass a pointer to a function in A to your B object, and call functions from A inside of B. This is known as a callback, and are used fairly frequently.

eli
  • 311
  • 1
  • 2
  • 10
0

The main reason is so that you can pass functions as arguments to other functions. For example imagine you want to implement a forEach() function that operates on data stored in an array. Then you want that forEach() function to take as arguments the array, and the function that you wish to apply to each element.

That's about the simplest example I can think of, but you can imagine other cases where passing functions in to other functions could be useful.

Also see: https://en.wikipedia.org/wiki/Functional_programming

Luke Walsh
  • 281
  • 1
  • 7