
In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a callback or callback function is any reference to
executable code that is passed as an
argument
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialect ...
to another piece of code; that code is expected to ''call back'' (execute) the callback function as part of its job. This execution may be immediate as in a synchronous callback, or it might happen at a later point in time as in an asynchronous callback.
Programming languages
A programming language is a system of notation for writing computer program, computer programs. Most programming languages are text-based formal languages, but they may also be visual programming language, graphical. They are a kind of computer ...
support callbacks in different ways, often implementing them with
subroutines
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
,
lambda expressions,
blocks, or
function pointers
A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function poin ...
.
Design
There are two types of callbacks, differing in how they control data flow at runtime: ''blocking callbacks'' (also known as ''synchronous callbacks'' or just ''callbacks'') and ''deferred callbacks'' (also known as ''asynchronous callbacks''). While blocking callbacks are invoked before a function returns (as in the C example below), deferred callbacks may be invoked after a function returns. Deferred callbacks are often used in the context of I/O operations or event handling, and are called by interrupts or by a different thread in case of multiple threads. Due to their nature, blocking callbacks can work without interrupts or multiple threads, meaning that blocking callbacks are not commonly used for synchronization or for delegating work to another thread.
Callbacks are used to program applications in
windowing systems. In this case, the application supplies (a reference to) a specific custom callback function for the operating system to call, which then calls this application-specific function in response to events like mouse clicks or key presses. A major concern here is the management of privilege and security: while the function is called from the operating system, it should not run with the same
privilege
Privilege may refer to:
Arts and entertainment
* ''Privilege'' (film), a 1967 film directed by Peter Watkins
* ''Privilege'' (Ivor Cutler album), 1983
* ''Privilege'' (Television Personalities album), 1990
* ''Privilege (Abridged)'', an alb ...
as the system. A solution to this problem is using
rings of protection.
Implementation
The form of a callback varies among
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s:
* In
assembly
Assembly may refer to:
Organisations and meetings
* Deliberative assembly, a gathering of members who use parliamentary procedure for making decisions
* General assembly, an official meeting of the members of an organization or of their representa ...
,
C,
C++,
Pascal,
Modula2 and similar languages, a machine-level
pointer
Pointer may refer to:
Places
* Pointer, Kentucky
* Pointers, New Jersey
* Pointers Airport, Wasco County, Oregon, United States
* The Pointers, a pair of rocks off Antarctica
People with the name
* Pointer (surname), a surname (including a list ...
to a function may be passed as an argument to another (internal or external) function. This is supported by most compilers and provides the advantage of using different languages together without special wrapper libraries or classes. One example may be the
Windows API that is directly (more or less) accessible by many different languages, compilers and assemblers.
* C++ allows objects to provide their own implementation of the function call operation. The
Standard Template Library
The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', ''co ...
accepts these objects (called ''
functors
In mathematics, specifically category theory, a functor is a mapping between categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) are associated to topological spaces, and ma ...
''), as well as function pointers, as parameters to various polymorphic algorithms.
* Many
dynamic languages, such as
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
,
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
,
Python,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
and
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
, simply allow a function object to be passed through.
*
CLI languages such as
C# and
VB.NET provide a
type-safe encapsulating reference, a "
delegate", to define well-typed
function pointer
A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function point ...
s. These can be used as callbacks.
* Events and
event handlers, as used in .NET languages, provide generalized syntax for callbacks.
* Functional languages generally support
first-class functions, which can be passed as callbacks to other functions, stored as data or returned from functions.
* Some languages, such as
Algol 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously ...
, Perl, Python,
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
,
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by ...
,
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
and later, newer versions of C# and VB.NET as well as most functional languages, allow unnamed blocks of code (
lambda expressions) to be supplied instead of references to functions defined elsewhere.
* In some languages, e.g.
Scheme,
ML, JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0), C++11 and later, Java (since 8), and many others, such functions can be
closures, i.e. they can access and modify variables locally defined in the context in which the function was defined. Note that Java cannot, however, modify the local variables in the enclosing scope.
* In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
languages without function-valued arguments, such as in
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
before its 8 version, callbacks can be simulated by passing an instance of an abstract class or interface, of which the receiver will call one or more methods, while the calling end provides a concrete implementation. Such objects are effectively a bundle of callbacks, plus the data they need to manipulate. They are useful in implementing various
design patterns such as
Visitor
A visitor, in English and Welsh law and history, is an overseer of an autonomous ecclesiastical or eleemosynary institution, often a charitable institution set up for the perpetual distribution of the founder's alms and bounty, who can inter ...
,
Observer, and
Strategy
Strategy (from Greek στρατηγία ''stratēgia'', "art of troop leader; office of general, command, generalship") is a general plan to achieve one or more long-term or overall goals under conditions of uncertainty. In the sense of the " a ...
.
Use
C
Callbacks have a wide variety of uses, for example in error signaling: a
Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, a ...
program might not want to terminate immediately when it receives
SIGTERM
Signals are standardized messages sent to a running program to trigger specific behavior, such as quitting or error handling. They are a limited form of inter-process communication (IPC), typically used in Unix, Unix-like, and other POSIX-co ...
, so to make sure that its termination is handled properly, 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
C code demonstrates the use of callbacks to display two numbers.
#include
#include
#include
/* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void))
/* A possible callback */
int overNineThousand(void)
/* Another possible callback. */
int meaningOfLife(void)
/* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void)
Example output:
and
and
42 and 42
Note 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
In computer science, information hiding is the principle of segregation of the ''design decisions'' in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decisio ...
: 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.
*
*/
#include
#include
typedef struct _MyMsg MyMsg;
void myfunc(MyMsg *msg)
/*
* Prototype declaration
*/
void (*callback)(MyMsg *);
int main(void)
The output after compilation:
$ gcc cbtest.c
$ ./a.out
App Id = 100
Msg = This is a test
This information hiding means that callbacks can be used when communicating between processes or threads, or through serialised communications and tabular data.
In C++,
functor
In mathematics, specifically category theory, a functor is a mapping between categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) are associated to topological spaces, an ...
is also commonly used beside the usage of function pointer in C.
C#
A simple callback in
C#:
public class Class1
public class Class2
Kotlin
A simple callback in
Kotlin:
fun main()
fun meaningOfLife(): Int
fun answer(question: String?, answer: () -> Int)
JavaScript
Callbacks are used in the implementation of languages such as
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, including support of JavaScript functions as callbacks through js-ctypes and in components such as addEventListener.
However, a native example of a callback can be written without any complex code:
function calculate(num1, num2, callbackFunction)
function calcProduct(num1, num2)
function calcSum(num1, num2)
// alerts 75, the product of 5 and 15
alert(calculate(5, 15, calcProduct));
// alerts 20, the sum of 5 and 15
alert(calculate(5, 15, calcSum));
First a function is defined with a parameter intended for callback: . Then a function that can be used as a callback to is defined, . Other functions may be used for , like . In this example, is invoked twice, once with as a callback and once with . The functions return the product and sum, respectively, and then the alert will display them to the screen.
In this primitive example, the use of a callback is primarily a demonstration of principle. One could simply call the callbacks as regular functions, . Callbacks are generally used when the function needs to perform events before the callback is executed, or when the function does not (or cannot) have meaningful return values to act on, as is the case for
Asynchronous JavaScript (based on timers) or
XMLHttpRequest requests. Useful examples can be found in
JavaScript libraries such as
jQuery where the .each() method iterates over an array-like object, the first argument being a callback that is performed on each iteration.
Red and REBOL
From the
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
above, here is how one would implement the same in either
REBOL or
Red (programming language). Notice the cleaner presentation of data as code.
* return is implied as the code in each function is the last line of the block
* As alert requires a string, form produces a string from the result of calculate
* The get-word! values (i.e., :calc-product and :calc-sum) trigger the interpreter to return the code of the function rather than evaluate with the function.
* The datatype! references in a block!
loat! integer!restrict the type of values passed as arguments.
Red itle: "Callback example"
calculate: func num1 [number!
num2 [number!">umber!.html" ;"title=" num1 [number!"> num1 [number!
num2 [number!
callback-function [function!]
][
callback-function num1 num2
]
calc-product: func num1 [number!
num2 [number!">umber!.html" ;"title=" num1 num1 [number!
num2 [number!">umber!"> num1 [number!
num2 [number!
num1 * num2
">umber!<_a>
____num2_[number!<_a>.html" ;"title="umber!"> num1 [number!
num2 [number!">umber!"> num1 [number!
num2 [number!
num1 * num2
calc-sum: func num1 [number!
num2 [number!">umber!.html" ;"title=" num1 num1 [number!
num2 [number!">umber!"> num1 [number!
num2 [number!
num1 + num2
]
; alerts 75, the product of 5 and 15
alert form calculate 5 15 :calc-product
; alerts 20, the sum of 5 and 15
alert form calculate 5 15 :calc-sum
Lua
A color tweening example using the
Roblox engine that takes an optional .done callback:
wait(1)
local DT = wait()
function tween_color(object, finish_color, fade_time)
local step_r = finish_color.r - object.BackgroundColor3.r
local step_g = finish_color.g - object.BackgroundColor3.g
local step_b = finish_color.b - object.BackgroundColor3.b
local total_steps = 1/(DT*(1/fade_time))
local completed;
coroutine.wrap(function()
for i = 0, 1, DT*(1 / fade_time) do
object.BackgroundColor3 = Color3.new (
object.BackgroundColor3.r + (step_r/total_steps),
object.BackgroundColor3.g + (step_g/total_steps),
object.BackgroundColor3.b + (step_b/total_steps)
)
wait()
end
if completed then
completed()
end
end)()
return
end
tween_color(some_object, Color3.new(1, 0, 0), 1).done(function()
print "Color tweening finished!"
end)
Python
A typical use of callbacks in Python (and other languages) is to assign events to UI elements.
Here is a very trivial example of the use of a callback in Python. First define two functions, the callback and the calling code,
then pass the callback function into the calling code.
>>> def get_square(val):
... """The callback."""
... return val ** 2
...
>>> def caller(func, val):
... return func(val)
...
>>> caller(get_square, 5)
25
Julia
Functions in Julia are
first-class citizen, so they can simply be passed to higher-level functions to be used (called) within the body of that functions.
Here the same example above in Julia:
julia> get_square(val) = val^2 # The callback
get_square (generic function with 1 method)
julia> caller(func,val) = func(val)
caller (generic function with 1 method)
julia> caller(get_square,5)
25
See also
*
Command pattern
*
Continuation-passing style
*
Event loop In computer science, the event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program. The event loop works by making a request to some internal or external "event provider" (that generally ...
*
Event-driven programming
*
Implicit invocation
*
Inversion of control
*
libsigc++, a callback library for C++
*
Signals and slots
*
User exit
References
{{reflist
External links
Basic Instincts: Implementing Callback Notifications Using DelegatesImplement Script Callback Framework in ASP.NETInterfacing C++ member functions with C libraries(archived from the original on July 6, 2011)
Articles with example C code
Subroutines