C Callbacks have a wide variety of uses, for example in error signaling: a
Unix program might not want to terminate immediately when it receives , so to make sure that its termination is handled properly, it would register the cleanup function as a callback. • include • include • include • include 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 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. • include 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 allows custom predicates to be specified to determine whether a program wishes to handle an event. In the following
C 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 • include 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 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 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 is a type-erased wrapper for any callable objects, introduced in
C++11: import std; using std::function; void performOperation(int a, function 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# 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 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 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 of the
jQuery library 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 ,
Ajax and
XMLHttpRequest. In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.
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
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() { 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 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: int) -> int: return val ** 2 def calculate(operate: Callableint], int], val: int) -> int: return operate(val) • prints: 25 print(calculate(square, 5))
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! [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 have the , and traits. fn call_with_one(func: F) -> usize where F: Fn(usize) -> usize { func(1) } let double = |x| x * 2; assert_eq!(call_with_one(double), 2); == See also ==