Conceptcore
Function pointers and delegates
Also called function pointer, procedure pointer, subroutine pointer, delegate, multicast delegate, method reference, std::function.
A function pointer holds the address of a function, and a call through it runs that function. A delegate in C# is a typed reference to a method and can hold an object and several methods.
- Applies to
- core-languages
Idea
A function pointer is a value that holds the address of a function. Wikipedia gives the definition: "A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data."1 A program can change the pointer at run time, so one call in the code can run different functions.
#include <stdio.h>
static int add(int a, int b) { return a + b; }
static int mul(int a, int b) { return a * b; }
int main(void) {
int (*op)(int, int) = add;
printf("%d\n", op(6, 7));
op = mul;
printf("%d\n", op(6, 7));
return 0;
}
13
42
The call op(6, 7) is the same both times. The first time op points to add, and the second time it points to mul.
A delegate is the form of this idea in C# and .NET. "A delegate is a type that represents references to methods with a particular parameter list and return type."2 A delegate can also hold the object for an instance method and a list of several methods.
How it works
- The type. The pointer has a type that gives the parameter types and the result type. In C,
int (*op)(int, int)declaresopas a pointer to a function that takes twointand returnsint. The C reference reads the declarator(*pf)(double)as an object of the type pointer to function that takesdoubleand returnsint3. - Taking the address. The name of a function converts to a pointer. "Because of the function-to-pointer conversion, the address-of operator is optional"4, so
op = addandop = &addare the same. - The call. "A pointer to function can be used on the left-hand side of the function call operator; this invokes the pointed-to function"4. The compiled code jumps to the address in the pointer.
- A value like any other. "Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc."4 The C library uses this for callbacks.
qsorttakes the comparison as the parameterint (*comp)(const void*, const void*)5.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has function types and function references such as ::add. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL has no function values. |
| Bash | Idiom | |
| PowerShell | Idiom | PowerShell has no function pointers. A variable can hold a script block or the command object from Get-Command, and the & operator calls it. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions. |
| CSS | Does not apply | CSS has no function values. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- C. Function pointers as above. A
typedefgives a short name to a function pointer type, as intypedef arr_t* (*fp)(void);6. "Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function)."4 A C function pointer holds only the function, so a callback API can take one more argument for the data. C11qsort_spasses its parametervoid* contextto the comparison function5. - C++. C++ has the function pointers of C. It also has pointers to member functions: "A pointer to non-static member function f which is a member of class C can be initialized with the expression &C::f exactly."7
std::functionholds any callable value: "Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions (via pointers thereto), lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members."8 - C#. Delegates. "A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure."9 "When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method."9
- Java. Java has no function pointers. A method reference such as
String::lengthmakes an object of a functional interface: "Functional interfaces provide target types for lambda expressions and method references."10 Method references "are compact, easy-to-read lambda expressions for methods that already have a name"11. - Go. Function values have a function type, and "The value of an uninitialized variable of function type is nil."12
- Rust. "The fn type is called a function pointer."13 "Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), meaning you can always pass a function pointer as an argument for a function that expects a closure."13
- Python, JavaScript and TypeScript. Functions are objects, so a variable holds the function itself and no pointer type is needed. In Python, "A user-defined function object is created by a function definition"14. See First-class function.
- Bash. Bash has no function pointers. A variable holds the name of a function. "When the name of a shell function is used as a simple command name, the shell executes the list of commands associated with that function name."15
import operator
def add(a, b):
return a + b
def apply(f, a, b):
return f(a, b)
op = add
print(op(6, 7))
op = operator.mul
print(op(6, 7))
print(apply(lambda a, b: a - b, 6, 7))
13
42
-1
- Verdict: native. A Python variable holds the function object itself, so no pointer type is needed.
operator.mulis a built-in function that a variable can hold in the same way.
#include <functional>
#include <iostream>
int add(int a, int b) { return a + b; }
int apply(const std::function<int(int, int)>& f, int a, int b) { return f(a, b); }
int main() {
int (*op)(int, int) = add;
std::cout << op(6, 7) << '\n';
std::function<int(int, int)> g = [](int a, int b) { return a * b; };
std::cout << g(6, 7) << '\n';
std::cout << apply([](int a, int b) { return a - b; }, 6, 7) << '\n';
}
13
42
-1
- Verdict: native.
opis a C function pointer.std::function<int(int, int)>holds a lambda, andapplytakes any callable with that signature.
import java.util.function.IntBinaryOperator;
public class Main {
static int add(int a, int b) {
return a + b;
}
static int mul(int a, int b) {
return a * b;
}
static int apply(IntBinaryOperator f, int a, int b) {
return f.applyAsInt(a, b);
}
public static void main(String[] args) {
IntBinaryOperator op = Main::add;
System.out.println(op.applyAsInt(6, 7));
op = Main::mul;
System.out.println(op.applyAsInt(6, 7));
System.out.println(apply((a, b) -> a - b, 6, 7));
}
}
13
42
-1
- Verdict: native. Java has no function pointers. The method references
Main::addandMain::mulmake objects of the functional interfaceIntBinaryOperator, and the call isapplyAsInt.
#include <stdio.h>
typedef int (*binop)(int, int);
static int add(int a, int b) { return a + b; }
static int mul(int a, int b) { return a * b; }
static int sub(int a, int b) { return a - b; }
static int apply(binop f, int a, int b) { return f(a, b); }
int main(void) {
binop op = add;
printf("%d\n", op(6, 7));
op = mul;
printf("%d\n", op(6, 7));
printf("%d\n", apply(sub, 6, 7));
return 0;
}
13
42
-1
- Verdict: native.
binopis atypedeffor a pointer to a function that takes twointand returnsint. The variableoppoints first toadd, then tomul.
using System;
delegate int BinOp(int a, int b);
class Program
{
static int Add(int a, int b)
{
return a + b;
}
static int Mul(int a, int b)
{
return a * b;
}
static int Apply(Func<int, int, int> f, int a, int b)
{
return f(a, b);
}
static void Main()
{
BinOp op = Add;
Console.WriteLine(op(6, 7));
op = Mul;
Console.WriteLine(op(6, 7));
Console.WriteLine(Apply((a, b) => a - b, 6, 7));
}
}
13
42
-1
- Verdict: native.
BinOpis a delegate type. The variableopholds the methodAdd, thenMul.Applytakes the library delegate typeFunc<int, int, int>.
function add(a, b) {
return a + b;
}
function mul(a, b) {
return a * b;
}
function apply(f, a, b) {
return f(a, b);
}
let op = add;
console.log(op(6, 7));
op = mul;
console.log(op(6, 7));
console.log(apply((a, b) => a - b, 6, 7));
13
42
-1
- Verdict: native. A JavaScript variable holds the function itself.
opholdsadd, thenmul.
type BinOp = (a: number, b: number) => number;
function add(a: number, b: number): number {
return a + b;
}
function mul(a: number, b: number): number {
return a * b;
}
function apply(f: BinOp, a: number, b: number): number {
return f(a, b);
}
let op: BinOp = add;
console.log(op(6, 7));
op = mul;
console.log(op(6, 7));
console.log(apply((a, b) => a - b, 6, 7));
13
42
-1
- Verdict: native. The type alias
BinOpgives the type of the function values, as a function pointer type does in C.
package main
import "fmt"
type binop func(int, int) int
func add(a, b int) int { return a + b }
func mul(a, b int) int { return a * b }
func apply(f binop, a, b int) int { return f(a, b) }
func main() {
op := binop(add)
fmt.Println(op(6, 7))
op = mul
fmt.Println(op(6, 7))
fmt.Println(apply(func(a, b int) int { return a - b }, 6, 7))
}
13
42
-1
- Verdict: native.
binopis a named function type. A variable of that type holdsadd, thenmul, andapplytakes a function literal.
type BinOp = fn(i32, i32) -> i32;
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn mul(a: i32, b: i32) -> i32 {
a * b
}
fn apply(f: BinOp, a: i32, b: i32) -> i32 {
f(a, b)
}
fn main() {
let mut op: BinOp = add;
println!("{}", op(6, 7));
op = mul;
println!("{}", op(6, 7));
println!("{}", apply(|a, b| a - b, 6, 7));
}
13
42
-1
- Verdict: native.
BinOpis the function pointer typefn(i32, i32) -> i32. The closure|a, b| a - bcaptures nothing, so it coerces to that type.
add() {
echo $(($1 + $2))
}
mul() {
echo $(($1 * $2))
}
sub() {
echo $(($1 - $2))
}
apply() {
local f=$1
shift
"$f" "$@"
}
op=add
"$op" 6 7
op=mul
"$op" 6 7
apply sub 6 7
13
42
-1
- Verdict: idiom. Bash has no function pointers. The variable
opholds the name of a function, andapplyruns the name that it gets as its first argument.
Variations and related ideas
- Function pointers as the first step. "Languages where functions are not first-class often still allow one to write higher-order functions through the use of features such as function pointers or delegates."16
- Bound methods. A C function pointer has no data. A C# delegate for an instance method keeps the object too9. "Delegates specify a method to call and optionally an object to call the method on."17
- Multicast delegates. A C# delegate can call several methods. "To add an extra method to the delegate's list of methods—the invocation list—simply requires adding two delegates using the addition or addition assignment operators ('+' or '+=')."9 "Delegates are used, among other things, to implement callbacks and event listeners."17
using System;
class Program
{
static void Main()
{
Action<string> log = s => Console.WriteLine("screen: " + s);
log += s => Console.WriteLine("file: " + s);
log("saved");
}
}
screen: saved
file: saved
- Wrappers for any callable. A C++
std::functioncan hold a function pointer, a lambda with captured variables or another function object8. One type covers all of them.
Pitfalls
A multicast delegate returns only the last result
A delegate with a return value and two methods runs both methods, but the caller gets only one result. "If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked."9
This code runs but gives a wrong answer on purpose.
using System;
class Program
{
static void Main()
{
Func<int, int> f = x => x + 1;
f += x => x * 10;
Console.WriteLine(f(5));
}
}
50
The first method gives 6, and the program loses it. Use multicast only for delegates that return void, such as Action and event handlers. To get all the results, keep the functions in a list and call each one.
A call through an empty wrapper
A C function pointer can be a null pointer4, a Go function value can be nil12, and a C++ std::function can be empty. The C++ reference says: "Invoking the target of an empty std::function results in std::bad_function_call exception being thrown."8 Check the value before the call, or make sure that it always has a target.
Hard declarations in C
The C declarator syntax nests. The C reference takes apart int (*(*foo)(double))[3] in five steps to show that foo is a "pointer to function taking double and returning pointer to array of 3 int"3. Give each function pointer type a name with typedef6.
Cost
A call through a function pointer is an indirect call, "because the function is being invoked indirectly through a variable instead of directly through a fixed identifier or address"1. The program reads the address from the variable before the jump. A C function pointer is one address. A C# delegate for an instance method also holds the object9, and a C++ std::function holds a copy of its target8.
History
Wikipedia lists PL/I, COBOL, Fortran and C among the third-generation languages with function pointers, and C++, C# and D among the object-oriented languages with them1. Wikipedia describes the delegate of .NET as "a form of type-safe function pointer used by the Common Language Infrastructure (CLI)"17.
References
- Function pointer, Wikipedia, the introduction
- Delegates, C# Programming Guide, the introduction
- Declarations, C reference, cppreference.com, Declarators, the example
- Pointer declaration, C reference, cppreference.com, Pointers to functions
- qsort, qsort_s, C reference, cppreference.com, the declaration
- Typedef declaration, C reference, cppreference.com, Example
- Pointer declaration, C++ reference, cppreference.com, Pointers to member functions
- std::function, C++ reference, cppreference.com, the introduction
- Using Delegates, C# Programming Guide, the whole page
- Package java.util.function, Java SE 25 API, the package description
- Method References, The Java Tutorials, the introduction; Kinds of Method References
- The Go Programming Language Specification, Function types
- Advanced Functions and Closures, The Rust Programming Language, Function Pointers
- Data model, The Python Language Reference, 3.2.8 Callable types
- Shell Functions, Bash Reference Manual, 3.3 Shell Functions
- First-class function, Wikipedia, Concepts
- Delegate (CLI), Wikipedia, the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag QXSYSW Edit this page History Report an error Markdown