Résumé
A function pointer, also called a subroutine pointer or procedure pointer, is a pointer referencing executable code, rather than data. Dereferencing the function pointer yields the referenced function, 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 allow different code to be executed at runtime. They can also be passed to a function to enable callbacks. Function pointers are supported by third-generation programming languages (such as PL/I, COBOL, Fortran, dBASE dBL, and C) and object-oriented programming languages (such as C++, C#, and D). The simplest implementation of a function (or subroutine) pointer is as a variable containing the address of the function within executable memory. Older third-generation languages such as PL/I and COBOL, as well as more modern languages such as Pascal and C generally implement function pointers in this manner. #Alternate C and C++ syntax 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 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) { return cm / 2.54; } // "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) { double (*func1)(double) = cm_to_inches; char * (*func2)(const char , int) = strchr; printf("%f %s", func1(15.0), func2("Wikipedia", 'p')); / prints "5.
À propos de ce résultat
Cette page est générée automatiquement et peut contenir des informations qui ne sont pas correctes, complètes, à jour ou pertinentes par rapport à votre recherche. Il en va de même pour toutes les autres pages de ce site. Veillez à vérifier les informations auprès des sources officielles de l'EPFL.