# Callback (computer programming)

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Callback_(computer_programming)
> Markdown URL: https://mediated.wiki/source/Callback_(computer_programming).md
> Source: https://en.wikipedia.org/wiki/Callback_(computer_programming)
> Source revision: 1355883917
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

Function reference passed to and called by another function

For a discussion of callback with computer modems, see [Callback (telecommunications)](/source/Callback_(telecommunications)).

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. Find sources: "Callback" computer programming – news · newspapers · books · scholar · JSTOR (September 2015) (Learn how and when to remove this message)

A callback is often back on the level of the original caller.

In [computer programming](/source/Computer_programming), a **callback** is a [programming pattern](/source/Programming_pattern) in which a [function](/source/Function_(computer_programming)) [reference](/source/Reference_(computer_science)) is passed from one context (consumer) to another (provider) such that the provider can call the function. If the function accesses [state](/source/State_(computer_science)) or [functionality](/source/Function_(computer_programming)) of the consumer, then the call is *back* to the consumer – backwards compared to the normal [flow of control](/source/Flow_of_control) in which a consumer calls a provider.

A function that accepts a callback [parameter](/source/Parameter_(computer_programming)) may be designed to call back before [returning](/source/Return_statement) to its caller. But, more typically, a callback reference is stored by the provider so that it can call the function later (as *deferred*). If the provider invokes the callback on the same [thread](/source/Thread_(computer_programming)) as the consumer, then the call is *blocking*, a.k.a. *[synchronous](/source/Synchronization_(computer_science))*. If instead, the provider invokes the callback on a different thread, then the call is *[non-blocking](/source/Non-blocking_algorithm)*, a.k.a. *asynchronous*.

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 difference between a general function reference and a callback can be subtle, and some use the terms interchangeably but distinction generally depends on programming intent. If the intent is like the [telephone callback](/source/Callback_(telecommunications)) – that the original [called party](/source/Called_party) communicates back to the original [caller](/source/Calling_party) – then it's a callback.

## Use

A blocking callback runs in the [execution](/source/Execution_(computing)) context of the function that passes the callback. A deferred callback can run in a different context such as during [interrupt](/source/Interrupt) or from a [thread](/source/Thread_(computing)). 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](/source/Graphical_user_interface) (GUI) of a program that runs in a [windowing system](/source/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](/source/Computer_mouse) clicks and [key](/source/Computer_keyboard) 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](/source/Polymorphism_(computer_science)). In the following pseudocode, say_hi can take either write_status or write_error.

from typing import Callable

def write_status(message: str) -> None:
    write(stdout, message)

def write_error(message: str) -> None:
    write(stderr, message)

def say_hi(write: Callable[[str], None]) -> None:
    write("Hello world")

## Implementation

The callback technology is implemented differently by [programming language](/source/Programming_language).

In [assembly](/source/Assembly_language), [C](/source/C_(programming_language)), [C++](/source/C%2B%2B), [Pascal](/source/Pascal_(programming_language)), [Modula2](/source/Modula2) and other languages, a callback function is stored internally as a [function pointer](/source/Function_pointer)[1]. Using the same storage allows different languages to directly share callbacks without a [design-time or runtime](/source/Program_lifecycle_phase) [interoperability](/source/Interoperability) [layer](/source/Abstraction_layer). For example, the [Windows API](/source/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](/source/Standard_Template_Library) accepts these objects (called *[functors](/source/Function_object)*) as parameters. Many [dynamic languages](/source/Dynamic_programming_language), such as [JavaScript](/source/JavaScript), [Lua](/source/Lua_(programming_language)), [Python](/source/Python_(programming_language)), [Perl](/source/Perl)[2][3] and [PHP](/source/PHP), allow a function object to be passed. [CLI languages](/source/List_of_CLI_languages) such as [C#](/source/C_Sharp_(programming_language)) and [VB.NET](/source/VB.NET) provide a [type-safe](/source/Type_safety) encapsulating function reference known as [delegate](/source/Delegate_(CLI)). Events and [event handlers](/source/Event_handlers), as used in .NET languages, provide for callbacks. Functional languages generally support [first-class functions](/source/First-class_functions), which can be passed as callbacks to other functions, stored as data or returned from functions.

Many languages, including Perl, Python, [Ruby](/source/Ruby_(programming_language)), [Smalltalk](/source/Smalltalk), [C++](/source/C%2B%2B) (11+), C# and VB.NET (new versions) and most functional languages, support [lambda expressions](/source/Lambda_(programming)), unnamed functions with inline syntax, that generally act as callbacks. In some languages, including [Scheme](/source/Scheme_(programming_language)), [ML](/source/ML_(programming_language)), JavaScript, Perl, Python, Smalltalk, PHP (since 5.3.0),[4] C++ (11+), Java (since 8),[5] and many others, a lambda can be a [closure](/source/Closure_(computer_science)), i.e. can access variables locally defined in the context in which the lambda is defined. In an [object-oriented programming](/source/Object-oriented_programming) language such as [Java](/source/Java_(programming_language)) 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](/source/PL%2FI) and [ALGOL 60](/source/ALGOL_60) 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.[6]

## Example code

### C

Callbacks have a wide variety of uses, for example in error signaling: a [Unix](/source/Unix) program might not want to terminate immediately when it receives [SIGTERM](/source/SIGTERM), so to make sure that its termination is handled properly, it would register the cleanup function as a callback.

#include <signal.h>
#include <stdlib.h>

#include <fcntl.h>
#include <sys/types>

struct Data {
    // ...
};

static struct Data data = {
    // initialize contents here
};
static volatile sigatomic_t flag = 0;

void cleanupHandler(int signum) {
    flag = 1;
    int saveFile = open("savefile.dat", O_WRONLY | O_CREATO, S_IWUSR);
    write(saveFile, data, sizeof data);
    close(saveFile);
}

int main(void) {
    signal(cleanupHandler, SIGTERM);
    doStuff();
}

Another common use for callbacks in C is with [C standard library](/source/C_standard_library) functions used for sorting (qsort()) and searching (lsearch(), bsearch()) where a comparator function is passed as an argument to the routine to determine the collation order.[7]

#include <stdlib.h>

struct Person {
    char name[20];
    int age;
};

Person people[1000];

// Collates people by age
int compareAges(struct Person* p1, struct Person* p2) {
    return p2->age - p1->age;
}

int main(void) {
    // ...
    int numberOfPeople = /* some number here */;

    qsort(numberOfPeople, sizeof (struct Person), people, compareAges);
    // ...
}

Callbacks may also be used to control whether a function acts or not: [Xlib](/source/Xlib) allows custom predicates to be specified to determine whether a program wishes to handle an event. In the following [C](/source/C_(programming_language)) code, function printNumber() uses parameter getNumber as a blocking callback. printNumber() is called with getAnswerToMostImportantQuestion() which acts as a callback function. When run the output is: "Value: 42".

#include <stdio.h>
#include <stdlib.h>

void printNumber(int (*getNumber)(void)) {
    int val = getNumber();
    printf("Value: %d\n", val);
}

int getAnswerToMostImportantQuestion(void) {
    return 42;
}

int main(void) {
    printNumber(getAnswerToMostImportantQuestion);
    return 0;
}

### C++

In C++, [functors](/source/Function_object) can be used in addition to function pointer. A functor is an object with operator() defined. For example, the objects in std::views are functors. This is an example of using functors in C++:

import std;

class MyCallback {
public:
    void operator()(int x) {
        std::println("Callback called with value: {}", x);
    }
};

template <typename Callback>
void performOperation(int a, Callback callback) {
    std::println("Performing operation on: {}", a);
    callback(a);
}

int main() {
    MyCallback callback;
    int value = 10;
    performOperation(value, callback);

    return 0;
}

std::function<R(Args...)> is a type-erased wrapper for any callable objects, introduced in [C++11](/source/C%2B%2B11):

import std;

using std::function;

void performOperation(int a, function<void(int)> callback) {
    std::println("Performing operation on: {}", a);
    callback(a);
}

int main() {
    int value = 10;
    performOperation(value, [](int x) -> void {
        std::println("Callback called with value: {}", x);
    });

    return 0;
}

### C#

In the following [C#](/source/C_Sharp_(programming_language)) code, method Helper.PerformAction uses parameter callback as a blocking callback. Helper.PerformAction is called with Log which acts as a callback function. When run, the following is written to the console: "Callback was: Hello world".

namespace Wikipedia.Examples;

using System;

class Helper
{
    public void PerformAction(Action<string> callback)
    {
        callback("Hello world");
    }
}

public class Main
{
    static void Log(string str)
    {
        Console.WriteLine($"Callback was: {str}");
    }

    static void Main(string[] args)
    {
        Helper helper = new();
        helper.PerformAction(Log);
    }
}

### JavaScript

In the following [JavaScript](/source/JavaScript) 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) {
    return operate(a, b);
}
function multiply(a, b) {
    return a * b;
}
function sum(a, b) {
    return a + b;
}
// outputs 20
alert(calculate(10, 2, multiply));
// outputs 12
alert(calculate(10, 2, sum));

The collection method .each() of the [jQuery](/source/JQuery) [library](/source/JavaScript_libraries) 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) {
  console.log(index + ": " + $(this).text());
});

Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found in addEventListener, [Ajax](/source/Ajax_(programming)) and [XMLHttpRequest](/source/XMLHttpRequest). [8]

In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.[9]

### Julia

In the following [Julia](/source/Julia_(programming_language)) code, function calculate accepts a parameter operate that is used as a blocking callback. calculate is called with square 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

### Kotlin

In the following [Kotlin](/source/Kotlin_(programming_language)) 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() {
    print("Enter the most important question: ")
    val question = readLine()
    askAndAnswer(question, ::getAnswerToMostImportantQuestion)
}

fun getAnswerToMostImportantQuestion(): Int {
    return 42
}

fun askAndAnswer(question: String?, getAnswer: () -> Int) {
    println("Question: $question")
    println("Answer: ${getAnswer()}")
}

### Lua

In this [Lua](/source/Lua) code, function calculate accepts the operation parameter which is used as a blocking callback. calculate is called with both add and multiply, and then uses an [anonymous function](/source/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](/source/Python_(programming_language)) code, function calculate accepts a parameter operate that is used as a blocking callback. calculate is called with square which acts as a callback function.

def square(val: int) -> int:
    return val ** 2

def calculate(operate: Callable[[int], int], val: int) -> int:
    return operate(val)

# prints: 25
print(calculate(square, 5))

### Red and REBOL

The following [REBOL](/source/REBOL)/[Red](/source/Red_(programming_language)) 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! [float! integer!] restrict the type of values passed as arguments.

Red [Title: "Callback example"]

calculate: func [
    num1 [number!]
    num2 [number!]
    callback-function [function!]
][
    callback-function num1 num2
]

calc-product: func [
    num1 [number!]
    num2 [number!]
][
    num1 * num2
]

calc-sum: func [
    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](/source/Rust_(programming_language)) have the Fn, FnMut and FnOnce traits.[10]

fn call_with_one<F>(func: F) -> usize
    where F: Fn(usize) -> usize {
    func(1)
}

let double = |x| x * 2;
assert_eq!(call_with_one(double), 2);

## See also

- [Computer programming portal](https://en.wikipedia.org/wiki/Portal:Computer_programming)

- [Command pattern](/source/Command_pattern)

- [Continuation-passing style](/source/Continuation-passing_style)

- [Event loop](/source/Event_loop)

- [Event-driven programming](/source/Event-driven_programming)

- [Implicit invocation](/source/Implicit_invocation)

- [Inversion of control](/source/Inversion_of_control)

- [libsigc++](/source/Libsigc%2B%2B), a callback library for C++

- [Signals and slots](/source/Signals_and_slots)

- [User exit](/source/User_exit)

## References

1. **[^](#cite_ref-1)** Gallaba, K., Mesbah, A., & Beschastnikh, I. (2015). Don't Call Us, We'll Call You: Characterizing Callbacks in Javascript. *2015 ACM/IEEE International Symposium on Empirical Software Engineering and Measurement (ESEM)*. https://doi.org/10.1109/esem.2015.7321196

1. **[^](#cite_ref-2)** ["Perl Cookbook - 11.4. Taking References to Functions"](http://www.unix.org.ua/orelly/perl/cookbook/ch11_05.htm). 2 July 1999. Retrieved 2008-03-03.

1. **[^](#cite_ref-3)** ["Advanced Perl Programming - 4.2 Using Subroutine References"](http://www.unix.org.ua/orelly/perl/advprog/ch04_02.htm). 2 July 1999. Retrieved 2008-03-03.

1. **[^](#cite_ref-4)** ["PHP Language Reference - Anonymous functions"](https://secure.php.net/manual/en/functions.anonymous.php). Retrieved 2011-06-08.

1. **[^](#cite_ref-5)** ["What's New in JDK 8"](http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html). *oracle.com*.

1. **[^](#cite_ref-6)** Belzer, Jack; Holzman, Albert G; Kent, Allen, eds. (1979). [*Encyclopedia of Computer Science and Technology: Volume 12*](https://books.google.com/books?id=IFmaqTI9-KsC&pg=PA164). Marcel Dekker, inc. p. 164. [ISBN](/source/ISBN_(identifier)) [0-8247-2262-0](https://en.wikipedia.org/wiki/Special:BookSources/0-8247-2262-0). Retrieved January 28, 2024.

1. **[^](#cite_ref-7)** Prinz, Peter; Crawford, Tony (Dec 12, 2015). *C in a Nutshell* (2nd ed.). Sebastopal California: [O'Reilly Media Inc](https://en.wikipedia.org/w/index.php?title=O%27Reilly_Media_Inc&action=edit&redlink=1). pp. 538–540, 374–377. [ISBN](/source/ISBN_(identifier)) [978-1-491-90475-6](https://en.wikipedia.org/wiki/Special:BookSources/978-1-491-90475-6).

1. **[^](#cite_ref-8)** ["Creating JavaScript callbacks in components"](https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components#JavaScript_functions_as_callbacks). Archive. *UDN Web Docs* (Documentation page). sec. JavaScript functions as callbacks. [Archived](https://web.archive.org/web/20211216020616/https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components) from the original on 2021-12-16. Retrieved 2021-12-16.

1. **[^](#cite_ref-9)** Holley, Bobby; Shepherd, Eric (eds.). ["Declaring and Using Callbacks"](https://developer.mozilla.org.cach3.com/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks). Docs. *[Mozilla Developer Network](/source/Mozilla_Developer_Network)* (Documentation page). [Archived](https://web.archive.org/web/20190117092921/https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks) from the original on 2019-01-17. Retrieved 2021-12-16.

1. **[^](#cite_ref-10)** ["Fn in std::ops - Rust"](https://doc.rust-lang.org/std/ops/trait.Fn.html). *doc.rust-lang.org*. Retrieved 18 January 2025.

## External links

- [Basic Instincts: Implementing Callback Notifications Using Delegates](https://learn.microsoft.com/en-us/archive/msdn-magazine/2002/december/using-net-implementing-callback-notifications-using-delegates) - [MSDN Magazine](/source/MSDN_Magazine), December 2002

- [Implement callback routines in Java](https://web.archive.org/web/20080916192721/http://www.javaworld.com/javaworld/javatips/jw-javatip10.html)

- [Implement Script Callback Framework in ASP.NET 1.x](https://www.codeproject.com/Articles/7865/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)

- [Style Case Study #2: Generic Callbacks](http://gotw.ca/gotw/083.htm)

---
Adapted from the Wikipedia article [Callback (computer programming)](https://en.wikipedia.org/wiki/Callback_(computer_programming)) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Callback_(computer_programming)?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
