What is callback function

P

PengYu.UT

Hi,

Would you tell me what callback function is used? Why we need it? I
searched the web. But most webpages only mention that how to use it but
not why to use it.

Best wishes,
Peng
 
J

John Carson

Hi,

Would you tell me what callback function is used? Why we need it? I
searched the web. But most webpages only mention that how to use it
but not why to use it.

Best wishes,
Peng

A callback function is a function that is passed to another function (in the
form of a pointer to the callback function) so that the second function can
call it. This is simply of way of making the second function more flexible
without the second function needing to know a lot of stuff. By passing
different callback functions, you can get different behaviour (different
comparison rules, different formatting, different whatever). Nowadays it is
more common in C++ to use function objects for this purpose rather than
functions.
 
O

osmium

Would you tell me what callback function is used? Why we need it? I
searched the web. But most webpages only mention that how to use it but
not why to use it.

qsort() and bsearch() in <cstdlib> both use it which gives a couple of nice
tangible examples. It allows qsort to sort an array of pretty much anything:
char, int, double, a particular field within a struct, .... . Note that
that code pre-dates templates in C++. For a C++ example, consider the
evaluation of a definite integral using Simpson's rule or some such. A
callback function providing f(x) can be provided for the equation being
evaluated.
 
K

Kyle Kolander

Hi,

Would you tell me what callback function is used? Why we need it? I
searched the web. But most webpages only mention that how to use it but
not why to use it.

Best wishes,
Peng

I'd also say that callback functions can be used for updates, sort of like
hooking into another function. For example, consider a function that
downloads files using http. Your application may want to display progress
to the user. You could pass a callback function (display progress) into the
download function so that it calls your display function everytime it reads
from the socket. At least that is my understanding... :)

Kyle
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top