Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Callback (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example code== === 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 [[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]] allows custom predicates to be specified to determine whether a program wishes to handle an event. In the following [[C (programming language)|C]] code, function <code>print_number</code> uses parameter <code>get_number</code> as a blocking callback. <code>print_number</code> is called with <code>get_answer_to_most_important_question</code> which acts as a callback function. When run the output is: "Value: 42". <syntaxhighlight lang="c"> #include <stdio.h> #include <stdlib.h> void print_number(int (*get_number)(void)) { int val = get_number(); printf("Value: %d\n", val); } int get_answer_to_most_important_question(void) { return 42; } int main(void) { print_number(get_answer_to_most_important_question); return 0; } </syntaxhighlight> === C++ === In C++, [[Function object|functor]] can be used in addition to function pointer. === C# === In the following [[C Sharp (programming language)|C#]] code, method <code>Helper.Method</code> uses parameter <code>callback</code> as a blocking callback. <code>Helper.Method</code> is called with <code>Log</code> which acts as a callback function. When run, the following is written to the console: "Callback was: Hello world". <syntaxhighlight lang="c#"> public class MainClass { static void Main(string[] args) { Helper helper = new Helper(); helper.Method(Log); } static void Log(string str) { Console.WriteLine($"Callback was: {str}"); } } public class Helper { public void Method(Action<string> callback) { callback("Hello world"); } } </syntaxhighlight> === Kotlin === In the following [[Kotlin (programming language)|Kotlin]] code, function <code>askAndAnswer</code> uses parameter <code>getAnswer</code> as a blocking callback. <code>askAndAnswer</code> is called with <code>getAnswerToMostImportantQuestion</code> which acts as a callback function. Running this will tell the user that the answer to their question is "42". <syntaxhighlight lang="kotlin"> 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()}") } </syntaxhighlight> === JavaScript === In the following [[JavaScript]] code, function <code>calculate</code> uses parameter <code>operate</code> as a blocking callback. <code>calculate</code> is called with <code>multiply</code> and then with <code>sum</code> which act as callback functions. <syntaxhighlight lang="javascript"> 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)); </syntaxhighlight> The collection method {{code|.each()}} of the [[jQuery]] [[JavaScript libraries|library]] uses the function passed to it as a blocking callback. It calls the callback for each item of the collection. For example: <syntaxhighlight lang="javascript"> $("li").each(function(index) { console.log(index + ": " + $(this).text()); }); </syntaxhighlight> Deferred callbacks are commonly used for handling events from the user, the client and timers. Examples can be found in {{code|addEventListener}}, [[Ajax (programming)|Ajax]] and <code>[[XMLHttpRequest]]</code>. <ref>{{cite web |url=https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components#JavaScript_functions_as_callbacks |title=Creating JavaScript callbacks in components |department=Archive |website=UDN Web Docs |at=sec. JavaScript functions as callbacks |language=en |type=Documentation page |accessdate=2021-12-16 |url-status=live|archive-url=https://web.archive.org/web/20211216020616/https://udn.realityripple.com/docs/Mozilla/Creating_JavaScript_callbacks_in_components |archive-date=2021-12-16 }}</ref> In addition to using callbacks in JavaScript source code, C functions that take a function are supported via js-ctypes.<ref>{{cite web |url=https://developer.mozilla.org.cach3.com/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks<!--This page is not properly rendered--> |title=Declaring and Using Callbacks |editor1-last=Holley |editor1-first=Bobby |editor2-last=Shepherd |editor2-first=Eric |department=Docs |website=[[Mozilla Developer Network]] |language=en |type=Documentation page |accessdate=2021-12-16 |url-status=live |archive-url=https://web.archive.org/web/20190117092921/https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks |archive-date=2019-01-17}}</ref> === Red and REBOL === The following [[REBOL]]/[[Red (programming language)|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. <syntaxhighlight lang="red"> 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 </syntaxhighlight> === Rust === [[Rust (programming language)|Rust]] have the {{Code|Fn}}, {{Code|FnMut}} and {{Code|FnOnce}} traits.<ref>{{cite web |title=Fn in std::ops - Rust |url=https://doc.rust-lang.org/std/ops/trait.Fn.html |website=doc.rust-lang.org |access-date=18 January 2025}}</ref> <syntaxhighlight lang="rust"> 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); </syntaxhighlight> ===Lua=== In this [[Lua]] code, function {{code|calculate}} accepts the {{code|operation}} parameter which is used as a blocking callback. {{code|calculate}} is called with both {{code|add}} and {{code|multiply}}, and then uses an [[anonymous function]] to divide. <syntaxhighlight lang="lua">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))</syntaxhighlight> === Python === In the following [[Python (programming language)|Python]] code, function {{code|calculate}} accepts a parameter {{code|operate}} that is used as a blocking callback. {{code|calculate}} is called with {{code|square}} which acts as a callback function. <syntaxhighlight lang="python"> def square(val): return val ** 2 def calculate(operate, val): return operate(val) calculate(square, 5) # outputs: 25 </syntaxhighlight> ===Julia=== In the following [[Julia (programming language)|Julia]] code, function {{code|calculate}} accepts a parameter {{code|operate}} that is used as a blocking callback. {{code|calculate}} is called with {{code|square}} which acts as a callback function. <syntaxhighlight lang="jlcon"> 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 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)