Home >Backend Development >C++ >Application scenarios of C++ function pointers
The function pointer in C refers to the variable pointing to the memory address of the function. It is often used in scenarios such as callback functions, dynamic binding, and event processing. For example, in the sorting algorithm, we can use function pointers to implement different comparison functions to flexibly choose the sorting algorithm.
C Application scenarios of function pointers
What is a function pointer?
In C, a function pointer is a pointer to a function. It is a variable pointing to the memory address of the function.
Declaration of function pointer
The declaration of function pointer is very similar to the declaration of ordinary function, except that an asterisk (*) is added in front of the function name:
typedef int (*FuncPtr)(int, int);
The above declaration defines a function pointer named FuncPtr
, which points to a function that accepts two parameters of type int
and returns an int
type The function.
Usage of function pointers
Function pointers can be used in the following scenarios:
Practical case: Sorting algorithm
We can use function pointers to implement different sorting algorithms. Here is a sort
function using a comparison function using a function pointer:
#include <algorithm> bool Ascending(int a, int b) { return a < b; } bool Descending(int a, int b) { return a > b; } void Sort(int* arr, int size, bool (*CompareFunc)(int, int)) { std::sort(arr, arr + size, CompareFunc); } int main() { int arr[] = {5, 3, 1, 2, 4}; int size = sizeof(arr) / sizeof(arr[0]); // 使用升序比较函数进行排序 Sort(arr, size, Ascending); // 使用降序比较函数进行排序 Sort(arr, size, Descending); return 0; }
In the above code, CompareFunc
is a function pointer to a function that accepts two int
type parameters and returns a bool
type comparison function. We define two comparison functions Ascending
and Descending
, which compare two numbers in ascending and descending order. The
Sort
function sorts the array arr
using the comparison function passed in. By using function pointers, we can flexibly choose different comparison functions to implement different sorting algorithms.
The above is the detailed content of Application scenarios of C++ function pointers. For more information, please follow other related articles on the PHP Chinese website!