Use
Callbacks have a wide variety of uses. For example, imagine a function that reads a configuration file and associates values with options. If the options are identified by a hash, then writing the function so that it takes a callback makes it more flexible: its user can choose whatever hashing algorithm is desired and the function will continue to work, since it uses the callback to turn option names into hashes; thus, callbacks allow the user of a function to fine-tune it at runtime. Another use is in error signaling. A Unix program, for example, might not want to terminate immediately when it receives SIGTERM; to make sure things get taken care of, it would register the cleanup function as a callback.
Callbacks may also be used to control whether a function acts or not: Xlib allows custom predicates to be specified to determine whether a program wishes to handle an event. The following code in C demonstrates the use of callbacks to display two numbers.
#includeThis should provide output similar to:
125185 and 89187225 9084 and 9441 42 and 42Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions (not shown in the above example). This allows correct information hiding: the code that passes a callback to a calling function does not need to know the parameter values that will be passed to the function. If it only passed the return value, then the parameters would need to be exposed publicly.
Another example:
/* * This is a simple C program to demonstrate the usage of callbacks * The callback function is in the same file as the calling code. * The callback function can later be put into external library like * e.g. a shared object to increase flexibility. * */ #includeThe output after compilation:
$ gcc cbtest.c $ ./a.out App Id = 100 Msg = This is a testThis information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data.
Read more about this topic: Callback (computer Programming)
Famous quotes containing the word use:
“... it is use, and use alone, which leads one of us, tolerably trained to recognize any criterion of grace or any sense of the fitness of things, to tolerate ... the styles of dress to which we are more or less conforming every day of our lives. Fifty years hence they will seem to us as uncultivated as the nose-rings of the Hottentot seem today.”
—Elizabeth Stuart Phelps (18441911)