Programming Search⌘K

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;
}
Output
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

  1. The type. The pointer has a type that gives the parameter types and the result type. In C, int (*op)(int, int) declares op as a pointer to a function that takes two int and returns int. The C reference reads the declarator (*pf)(double) as an object of the type pointer to function that takes double and returns int3.
  2. 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 = add and op = &add are the same.
  3. 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.
  4. 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. qsort takes the comparison as the parameter int (*comp)(const void*, const void*)5.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin has function types and function references such as ::add. No example file exists because kotlinc is not installed.
SQLDoes not applyStandard SQL has no function values.
BashIdiom
PowerShellIdiomPowerShell 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.
HTMLDoes not applyHTML is a markup language and has no functions.
CSSDoes not applyCSS has no function values.
Regular expressionsDoes not applyA regular expression has no functions.
  • C. Function pointers as above. A typedef gives a short name to a function pointer type, as in typedef 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. C11 qsort_s passes its parameter void* context to 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::function holds 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::length makes 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
PythonGitHub
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))
Output
13
42
-1
  • Verdict: native. A Python variable holds the function object itself, so no pointer type is needed. operator.mul is 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';
}
Output
13
42
-1
  • Verdict: native. op is a C function pointer. std::function<int(int, int)> holds a lambda, and apply takes any callable with that signature.
JavaGitHub
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));
    }
}
Output
13
42
-1
  • Verdict: native. Java has no function pointers. The method references Main::add and Main::mul make objects of the functional interface IntBinaryOperator, and the call is applyAsInt.
#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;
}
Output
13
42
-1
  • Verdict: native. binop is a typedef for a pointer to a function that takes two int and returns int. The variable op points first to add, then to mul.
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));
    }
}
Output
13
42
-1
  • Verdict: native. BinOp is a delegate type. The variable op holds the method Add, then Mul. Apply takes the library delegate type Func<int, int, int>.
JavaScriptGitHub
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));
Output
13
42
-1
  • Verdict: native. A JavaScript variable holds the function itself. op holds add, then mul.
TypeScriptGitHub
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));
Output
13
42
-1
  • Verdict: native. The type alias BinOp gives 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))
}
Output
13
42
-1
  • Verdict: native. binop is a named function type. A variable of that type holds add, then mul, and apply takes a function literal.
RustGitHub
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));
}
Output
13
42
-1
  • Verdict: native. BinOp is the function pointer type fn(i32, i32) -> i32. The closure |a, b| a - b captures nothing, so it coerces to that type.
BashGitHub
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
Output
13
42
-1
  • Verdict: idiom. Bash has no function pointers. The variable op holds the name of a function, and apply runs the name that it gets as its first argument.
  • 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");
    }
}
Output
screen: saved
file: saved
  • Wrappers for any callable. A C++ std::function can 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));
    }
}
Output
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

  1. Function pointer, Wikipedia, the introduction
  2. Delegates, C# Programming Guide, the introduction
  3. Declarations, C reference, cppreference.com, Declarators, the example
  4. Pointer declaration, C reference, cppreference.com, Pointers to functions
  5. qsort, qsort_s, C reference, cppreference.com, the declaration
  6. Typedef declaration, C reference, cppreference.com, Example
  7. Pointer declaration, C++ reference, cppreference.com, Pointers to member functions
  8. std::function, C++ reference, cppreference.com, the introduction
  9. Using Delegates, C# Programming Guide, the whole page
  10. Package java.util.function, Java SE 25 API, the package description
  11. Method References, The Java Tutorials, the introduction; Kinds of Method References
  12. The Go Programming Language Specification, Function types
  13. Advanced Functions and Closures, The Rust Programming Language, Function Pointers
  14. Data model, The Python Language Reference, 3.2.8 Callable types
  15. Shell Functions, Bash Reference Manual, 3.3 Shell Functions
  16. First-class function, Wikipedia, Concepts
  17. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/QXSYSW/text.yaml