HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a callback is a function that is stored as data (a
reference A reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''nam ...
) and designed to be called by another function often ''back'' to the original
abstraction layer In computing, an abstraction layer or abstraction level is a way of hiding the working details of a subsystem. Examples of software models that use layers of abstraction include the OSI model for network protocols, OpenGL, and other graphics libra ...
. A function that accepts a callback
parameter A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
may be designed to call back before returning to its caller which is known as '' synchronous'' or ''blocking''. The function that accepts a callback may be designed to store the callback so that it can be called back after returning which is known as ''asynchronous'', '' non-blocking'' or ''deferred''. Programming languages support callbacks in different ways such as function pointers, lambda expressions and blocks. A callback can be likened to leaving instructions with a tailor for what to do when a suit is ready, such as calling a specific phone number or delivering it to a given address. These instructions represent a callback: a function provided in advance to be executed later, often by a different part of the system and not necessarily by the one that received it. The term ''callback'' can be misleading, as it does not necessarily imply a return to the original caller, unlike a telephone callback. Mesa programming language formalised the callback mechanism used in Programming Languages. By passing a procedure as a parameter, Mesa essentially delegated the execution of that procedure to a later point in time when a specific event occurred, similar to how callbacks are implemented in modern programming languages.


Use

A blocking callback runs in the
execution Capital punishment, also known as the death penalty and formerly called judicial homicide, is the state-sanctioned killing of a person as punishment for actual or supposed misconduct. The sentence ordering that an offender be punished in ...
context of the function that passes the callback. A deferred callback can run in a different context such as during
interrupt In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted ...
or from a thread. As such, a deferred callback can be used for synchronization and delegating work to another thread.


Event handling

A callback can be used for event handling. Often, consuming code registers a callback for a particular type of event. When that event occurs, the callback is called. Callbacks are often used to program the
graphical user interface A graphical user interface, or GUI, is a form of user interface that allows user (computing), users to human–computer interaction, interact with electronic devices through Graphics, graphical icon (computing), icons and visual indicators such ...
(GUI) of a program that runs in a windowing system. The application supplies a reference to a custom callback function for the windowing system to call. The windowing system calls this function to notify the application of events like
mouse A mouse (: mice) is a small rodent. Characteristically, mice are known to have a pointed snout, small rounded ears, a body-length scaly tail, and a high breeding rate. The best known mouse species is the common house mouse (''Mus musculus'' ...
clicks and key presses.


Asynchronous action

A callback can be used to implement asynchronous processing. A caller requests an action and provides a callback to be called when the action completes which might be long after the request is made.


Polymorphism

A callback can be used to implement polymorphism. In the following pseudocode, can take either or . def write_status(message: str): write(stdout, message) def write_error(message: str): write(stderr, message) def say_hi(write): write("Hello world")


Implementation

The callback technology is implemented differently by
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
. In assembly, C, C++, Pascal, Modula2 and other languages, a callback function is stored internally as a
function pointer A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments ...
. Using the same storage allows different languages to directly share callbacks without a design-time or runtime interoperability layer. For example, the Windows API is accessible via multiple languages, compilers and assemblers. C++ also allows objects to provide an implementation of the function call operation. The Standard Template Library accepts these objects (called '' functors'') as parameters. Many dynamic languages, such as
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
, Lua, Python,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
and PHP, allow a function object to be passed. CLI languages such as C# and VB.NET provide a type-safe encapsulating function reference known as delegate. Events and event handlers, as used in .NET languages, provide for callbacks. Functional languages generally support
first-class functions In computer science, a programming language is said to have first-class functions if it treats function (programming), functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning ...
, which can be passed as callbacks to other functions, stored as data or returned from functions. Many languages, including Perl, Python,
Ruby 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 sapph ...
,
Smalltalk Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
, C++ (11+), C# and VB.NET (new versions) and most functional languages, support lambda expressions, unnamed functions with inline syntax, that generally acts as callbacks.. In some languages, including Scheme, ML, JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0), C++ (11+), Java (since 8), and many others, a lambda can be a closure, i.e. can access variables locally defined in the context in which the lambda is defined. In an
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
language such as
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
versions before function-valued arguments, the behavior of a callback can be achieved by passing an object that implements an interface. The methods of this object are callbacks. In
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
and
ALGOL 60 ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a ...
a callback procedure may need to be able to access local variables in containing blocks, so it is called through an ''entry variable'' containing both the entry point and context information.


Example code


C

Callbacks have a wide variety of uses, for example in error signaling: a
Unix Unix (, ; trademarked as UNIX) is a family of multitasking, multi-user 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, 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 Xlib (also known as libX11) is an X Window System protocol client library (computer science), library written in the C (programming language), C programming language. It contains subroutine, functions for interacting with an X Server (computi ...
allows custom predicates to be specified to determine whether a program wishes to handle an event. In the following C code, function print_number uses parameter get_number as a blocking callback. print_number is called with get_answer_to_most_important_question which acts as a callback function. When run the output is: "Value: 42". #include #include void print_number(int (*get_number)(void)) int get_answer_to_most_important_question(void) int main(void)


C++

In C++,
functor In mathematics, specifically category theory, a functor is a Map (mathematics), mapping between Category (mathematics), categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) ar ...
can be used in addition to function pointer.


C#

In the following C# code, method Helper.Method uses parameter callback as a blocking callback. Helper.Method is called with Log which acts as a callback function. When run, the following is written to the console: "Callback was: Hello world". public class MainClass public class Helper


Kotlin

In the following Kotlin code, function askAndAnswer uses parameter getAnswer as a blocking callback. askAndAnswer is called with getAnswerToMostImportantQuestion which acts as a callback function. Running this will tell the user that the answer to their question is "42". fun main() fun getAnswerToMostImportantQuestion(): Int fun askAndAnswer(question: String?, getAnswer: () -> Int)


JavaScript

In the following
JavaScript JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
code, function calculate uses parameter operate as a blocking callback. calculate is called with multiply and then with sum which act as callback functions. function calculate(a, b, operate) function multiply(a, b) function sum(a, b) // outputs 20 alert(calculate(10, 2, multiply)); // outputs 12 alert(calculate(10, 2, sum)); The collection method of the jQuery
library A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
uses the function passed to it as a blocking callback. It calls the callback for each item of the collection. For example: $("li").each(function(index) ); Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found in ,
Ajax Ajax may refer to: Greek mythology and tragedy * Ajax the Great, a Greek mythological hero, son of King Telamon and Periboea * Ajax the Lesser, a Greek mythological hero, son of Oileus, the king of Locris * Ajax (play), ''Ajax'' (play), by the an ...
and XMLHttpRequest. In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.


Red and REBOL

The following REBOL/ Red code demonstrates callback use. * 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


Rust

Rust (programming language), Rust have the , and traits. fn call_with_one(func: F) -> usize where F: Fn(usize) -> usize let double = , x, x * 2; assert_eq!(call_with_one(double), 2);


Lua

In this Lua code, function accepts the parameter which is used as a blocking callback. is called with both and , and then uses an anonymous function to divide. function calculate(a, b, operation) return operation(a, b) end function multiply(a, b) return a * b end function add(a, b) return a + b end print(calculate(10, 20, multiply)) -- outputs 200 print(calculate(10, 20, add)) -- outputs 30 -- an example of a callback using an anonymous function print(calculate(10, 20, function(a, b) return a / b -- outputs 0.5 end))


Python

In the following Python code, function accepts a parameter that is used as a blocking callback. is called with which acts as a callback function. def square(val): return val ** 2 def calculate(operate, val): return operate(val) calculate(square, 5) # outputs: 25


Julia

In the following Julia code, function accepts a parameter that is used as a blocking callback. is called with which acts as a callback function. julia> square(val) = val^2 square (generic function with 1 method) julia> calculate(operate, val) = operate(val) calculate (generic function with 1 method) julia> calculate(square, 5) 25


See also

* Command pattern * Continuation-passing style * Event loop *
Event-driven programming In computer programming, event-driven programming is a programming paradigm in which the Control flow, flow of the program is determined by external Event (computing), events. User interface, UI events from computer mouse, mice, computer keyboard, ...
* 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 Delegates
- MSDN Magazine, December 2002
Implement callback routines in Java

Implement Script Callback Framework in ASP.NET 1.x
- Code Project, 2 August 2004 * Interfacing C++ member functions with C libraries (archived from the original on July 6, 2011)

Articles with example C code Articles with example C++ code Articles with example C Sharp code Articles with example JavaScript code Articles with example Julia code Articles with example Python (programming language) code Articles with example Rust code Subroutines