sekhu cool
sekhu cool

Reputation: 45

Use of function pointer in C

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.

Upvotes: 2

Views: 791

Answers (5)

Jay
Jay

Reputation: 24905

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.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340506

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.

Upvotes: 1

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

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.

Upvotes: 0

amit
amit

Reputation: 178521

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.

Upvotes: 5

justin
justin

Reputation: 104718

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.

Upvotes: 11

Related Questions