2

What is the advantage of passing a function as an argument to another function when we can use the function just by calling that function.

1
  • 1
    Essentially, a function pointer allows calling an unknown function until runtime. Calling a regular function requires you know the function name and that it's available at compile time. Commented Mar 12, 2012 at 14:26

5 Answers 5

11

It's one way to simulate polymorphism and/or callbacks.

A program or client may benefit from client entry points in some contexts. This is a common way to achieve that. It can be used improve modularity or improve physical separation of multiple implementations.

Sign up to request clarification or add additional context in comments.

Comments

5

Using function pointers you can create dynamic dispatch behavior. The dynamic "type", and not the static "type" will "determine" which function will be invoked.

This concept is very important in OOP languages, and can be created using function pointers.

Comments

1

Because when the function that takes the function pointer is written, it's not necessarily known what function it should call (I hope that makes some sense). Also, the function might be asked to use different function pointers to do different things.

for example, the C library has the qsort() function. It takes a function pointer to perform the comparison of the objects being sorted. So, when qsort() itself is written, it (or the programmer writing it) have no idea what kinds of objects it's going to be asked to sort. So a function pointer is used to provide that capability.

Also, qsort() may be asked to sort ints in one call, and struct foo objects immediately after. Passing a function pointer allows qsort() to be written in such way that it doesn't need to know much about the items being sorted. That information (the size of the objects being sorted and how to compare them) can be passed to it as parameters.

Comments

1

As correctly pointed out by Justin above, it is used for simualting Polymorphism and callbacks.

You can refer to this link to get details on function pointers and how to use them.

Comments

0

If you don't know in advance (at compile time) which function you're going to use, then it's useful that you can put a (pointer to the) function into a variable.

It's like, what's the advantage of using a variable int x when you could just write a constant 42.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.