HOME

TheInfoList



OR:

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory.
Dereferencing In computer programming, the dereference operator or indirection operator, sometimes denoted by "*" (i.e. an asterisk), is a unary operator (i.e. one with a single operand) found in List of C-family programming languages, C-like languages that in ...
the function pointer yields the referenced
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
, which can be invoked and passed arguments just as in a normal function call. Such an invocation is also known as an "indirect" call, because the function is being invoked ''indirectly'' through a variable instead of ''directly'' through a fixed identifier or address. Function pointers can be used to simplify code by providing a simple way to select a function to execute based on run-time values. Function pointers are supported by third-generation
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
s (such as
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
,
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
, Fortran, dBASE dBL, and C) and
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
languages (such as
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, C#, and D).


Simple function pointers

The simplest implementation of a function (or subroutine) pointer is as a
variable Variable may refer to: * Variable (computer science), a symbolic name associated with a value and whose associated value may be changed * Variable (mathematics), a symbol that represents a quantity in a mathematical expression, as used in many ...
containing the
address An address is a collection of information, presented in a mostly fixed format, used to give the location of a building, apartment, or other structure or a plot of land, generally using political boundaries and street names as references, along ...
of the function within executable memory. Older third-generation languages such as
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. I ...
and
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
, as well as more modern languages such as Pascal and C generally implement function pointers in this manner.


Example in C

The following C program illustrates the use of two function pointers: * ''func1'' takes one double-precision (double) parameter and returns another double, and is assigned to a function which converts centimeters to inches. * ''func2'' takes a pointer to a constant character array as well as an integer and returns a pointer to a character, and is assigned to a
C string handling The C programming language has a set of functions implementing operations on strings (character strings and byte strings) in its standard library. Various operations, such as copying, concatenation, tokenization and searching are supported. ...
function which returns a pointer to the first occurrence of a given character in a character array. #include /* for printf */ #include /* for strchr */ double cm_to_inches(double cm) // "strchr" is part of the C string handling (i.e., no need for declaration) // See https://en.wikipedia.org/wiki/C_string_handling#Functions int main(void) The next program uses a function pointer to invoke one of two functions (sin or cos) indirectly from another function (compute_sum, computing an approximation of the function's
Riemann integration In the branch of mathematics known as real analysis, the Riemann integral, created by Bernhard Riemann, was the first rigorous definition of the integral of a function on an interval. It was presented to the faculty at the University of Göt ...
). The program operates by having function main call function compute_sum twice, passing it a pointer to the library function sin the first time, and a pointer to function cos the second time. Function compute_sum in turn invokes one of the two functions indirectly by dereferencing its function pointer argument funcp multiple times, adding together the values that the invoked function returns and returning the resulting sum. The two sums are written to the standard output by main. #include #include // Function taking a function pointer as an argument double compute_sum(double (*funcp)(double), double lo, double hi) double square(double x) int main(void)


Functors

Functors, or function objects, are similar to function pointers, and can be used in similar ways. A functor is an object of a class type that implements the function-call operator, allowing the object to be used within expressions using the same syntax as a function call. Functors are more powerful than simple function pointers, being able to contain their own data values, and allowing the programmer to emulate closures. They are also used as callback functions if it is necessary to use a member function as a callback function. Many "pure" object-oriented languages do not support function pointers. Something similar can be implemented in these kinds of languages, though, using
references Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name'' ...
to
interfaces Interface or interfacing may refer to: Academic journals * Interface (journal), ''Interface'' (journal), by the Electrochemical Society * ''Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Lin ...
that define a single
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
(member function).
CLI languages CLI languages are computer programming languages that are used to produce libraries and programs that conform to the Common Language Infrastructure (CLI) specifications. With some notable exceptions, most CLI languages compile entirely to the Com ...
such as C# and
Visual Basic .NET Visual Basic, originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visua ...
implement
type-safe In computer science, type safety and type soundness are the extent to which a programming language discourages or prevents type errors. Type safety is sometimes alternatively considered to be a property of facilities of a computer language; that is ...
function pointers with
delegate Delegate or delegates may refer to: * Delegate, New South Wales, a town in Australia * Delegate (CLI), a computer programming technique * Delegate (American politics), a representative in any of various political organizations * Delegate (Unit ...
s. In other languages that support
first-class function In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. This means the language supports passing functions as arguments to other functions, returning them as the values from ...
s, functions are regarded as data, and can be passed, returned, and created dynamically directly by other functions, eliminating the need for function pointers. Extensively using function pointers to call functions may produce a slow-down for the code on modern processors, because a
branch predictor In computer architecture, a branch predictor is a digital circuit that tries to guess which way a branch (e.g., an if–then–else structure) will go before this is known definitively. The purpose of the branch predictor is to improve the flow ...
may not be able to figure out where to branch to (it depends on the value of the function pointer at run time) although this effect can be overstated as it is often amply compensated for by significantly reduced non-indexed table lookups.


Method pointers

C++ includes support for
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, so classes can have
methods Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
(usually referred to as member functions). Non-static member functions (instance methods) have an implicit parameter (the ''
this This may refer to: * ''This'', the singular proximal demonstrative pronoun Places * This, or ''Thinis'', an ancient city in Upper Egypt * This, Ardennes, a commune in France People with the surname * Hervé This, French culinary chemist Arts, e ...
'' pointer) which is the pointer to the object it is operating on, so the type of the object must be included as part of the type of the function pointer. The method is then used on an object of that class by using one of the "pointer-to-member" operators: .* or ->* (for an object or a pointer to object, respectively). Although function pointers in C and C++ can be implemented as simple addresses, so that typically sizeof(Fx)

sizeof(void *)
, member pointers in C++ are sometimes implemented as "
fat pointer In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
s", typically two or three times the size of a simple function pointer, in order to deal with virtual methods and
virtual inheritance Virtual inheritance is a C++ technique that ensures only one copy of a base classs member variables are inherited by grandchild derived classes. Without virtual inheritance, if two classes B and C inherit from a class A, and a class D inherits fr ...
.


In C++

In C++, in addition to the method used in C, it is also possible to use the C++ standard library class template , of which the instances are function objects: #include #include static double derivative(const std::function &f, double x0, double eps) static double f(double x) int main()


Pointers to member functions in C++

This is how C++ uses function pointers when dealing with member functions of classes or structs. These are invoked using an object pointer or a this call. They are type safe in that you can only call members of that class (or derivatives) using a pointer of that type. This example also demonstrates the use of a typedef for the pointer to member function added for simplicity. Function pointers to static member functions are done in the traditional 'C' style because there is no object pointer for this call required. #include using namespace std; class Foo ; int bar1(int i, int j, Foo* pFoo, int(Foo::*pfn)(int,int)) typedef int(Foo::*Foo_pfn)(int,int); int bar2(int i, int j, Foo* pFoo, Foo_pfn pfn) typedef int(*PFN)(int); int bar3(int i, PFN pfn) int main()


Alternate C and C++ syntax

The C and C++ syntax given above is the canonical one used in all the textbooks - but it's difficult to read and explain. Even the above typedef examples use this syntax. However, every C and C++ compiler supports a more clear and concise mechanism to declare function pointers: use typedef, but ''don't'' store the pointer as part of the definition. Note that the only way this kind of typedef can actually be used is with a pointer - but that highlights the pointer-ness of it.


C and C++

// This declares 'F', a function that accepts a 'char' and returns an 'int'. Definition is elsewhere. int F(char c); // This defines 'Fn', a type of function that accepts a 'char' and returns an 'int'. typedef int Fn(char c); // This defines 'fn', a variable of type pointer-to-'Fn', and assigns the address of 'F' to it. Fn *fn = &F; // Note '&' not required - but it highlights what is being done. // This calls 'F' using 'fn', assigning the result to the variable 'a' int a = fn('A'); // This defines 'Call', a function that accepts a pointer-to-'Fn', calls it, and returns the result int Call(Fn *fn, char c) // Call(fn, c) // This calls function 'Call', passing in 'F' and assigning the result to 'call' int call = Call(&F, 'A'); // Again, '&' is not required // LEGACY: Note that to maintain existing code bases, the above definition style can still be used first; // then the original type can be defined in terms of it using the new style. // This defines 'PFn', a type of pointer-to-type-Fn. typedef Fn *PFn; // 'PFn' can be used wherever 'Fn *' can PFn pfn = F; int CallP(PFn fn, char c);


C++

These examples use the above definitions. In particular, note that the above definition for Fn can be used in pointer-to-member-function definitions: // This defines 'C', a class with similar static and member functions, // and then creates an instance called 'c' class C c; // C // This defines 'p', a pointer to 'C' and assigns the address of 'c' to it C *p = &c; // This assigns a pointer-to-'Static' to 'fn'. // Since there is no 'this', 'Fn' is the correct type; and 'fn' can be used as above. fn = &C::Static; // This defines 'm', a pointer-to-member-of-'C' with type 'Fn', // and assigns the address of 'C::Member' to it. // You can read it right-to-left like all pointers: // "'m' is a pointer to member of class 'C' of type 'Fn'" Fn C::*m = &C::Member; // This uses 'm' to call 'Member' in 'c', assigning the result to 'cA' int cA = (c.*m)('A'); // This uses 'm' to call 'Member' in 'p', assigning the result to 'pA' int pA = (p->*m)('A'); // This defines 'Ref', a function that accepts a reference-to-'C', // a pointer-to-member-of-'C' of type 'Fn', and a 'char', // calls the function and returns the result int Ref(C &r, Fn C::*m, char c) // Ref(r, m, c) // This defines 'Ptr', a function that accepts a pointer-to-'C', // a pointer-to-member-of-'C' of type 'Fn', and a 'char', // calls the function and returns the result int Ptr(C *p, Fn C::*m, char c) // Ptr(p, m, c) // LEGACY: Note that to maintain existing code bases, the above definition style can still be used first; // then the original type can be defined in terms of it using the new style. // This defines 'FnC', a type of pointer-to-member-of-class-'C' of type 'Fn' typedef Fn C::*FnC; // 'FnC' can be used wherever 'Fn C::*' can FnC fnC = &C::Member; int RefP(C &p, FnC m, char c);


See also

* Delegation (computing) *
Function object In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). Function objects are often c ...
* Higher-order function *
Procedural parameter In computing, a procedural parameter is a parameter of a procedure that is itself a procedure. This concept is an extremely powerful and versatile programming tool, because it allows programmers to modify certain steps of a library procedure in ...
* Closure *
Anonymous function In computer programming, an anonymous function (function literal, lambda abstraction, lambda function, lambda expression or block) is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to ...
s


References


External links


FAQ on Function Pointers
things to avoid with function pointers, some information on using
function object In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). Function objects are often c ...
s
Function Pointer Tutorials
a guide to C/C++ function pointers, callbacks, and
function object In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax (a function parameter that can also be a function). Function objects are often c ...
s (functors)
Member Function Pointers and the Fastest Possible C++ Delegates
CodeProject article by Don Clugston

, C++ documentation and tutorials

{{Webarchive, url=https://web.archive.org/web/20190609120644/http://www.onlinecomputerteacher.net/pointers-in-c.html , date=2019-06-09 a visual guide of pointers in C
Secure Function Pointer and Callbacks in Windows Programming
CodeProject article by R. Selvam

Function Pointers in C by "The C Book"

Function Pointer in dBASE dBL Data types Subroutines Articles with example C code Articles with example C++ code de:Zeiger (Informatik)#Funktionszeiger (Methodenzeiger)