Home  >  Article  >  Backend Development  >  How do function pointers work in C++?

How do function pointers work in C++?

PHPz
PHPzOriginal
2024-06-04 17:37:10835browse

In C++, a function pointer is a variable pointing to a function, which can dynamically pass or store the function as a parameter. The syntax is: type name * function name. When allocating, use the function pointer address and dereference it when calling. For example, when calculating the maximum value using a function pointer, the calculation is performed by allocating the function pointer and calling it.

函数指针在 C++ 中如何工作?

How function pointers work in C++

In C++, a function pointer is a variable that points to a function. It allows us to dynamically pass functions as parameters or store them in data structures.

Syntax

The function pointer is declared like a regular function, but the type name is followed by an asterisk (*):

typedef void (*FunctionPointer)(int);

Assignment

We can do it like Assign a function address to a function pointer like an ordinary pointer:

FunctionPointer fp = &myFunction;

Call

We can call it by dereferencing the function pointer:

fp(10);

Practical case

Let's consider a program that uses function pointers to calculate the maximum of two numbers:

#include <iostream>

using namespace std;

// 最大值函数
int max(int a, int b) {
  return a > b ? a : b;
}

// 函数指针比较函数
int compare(int a, int b, int (*fp)(int, int)) {
  return fp(a, b);
}

int main() {
  // 分配函数指针并调用它来计算两数的最大值
  int (*fp)(int, int) = &max;
  int result = compare(5, 10, fp);

  // 打印结果
  cout << "最大值:" << result << endl;

  return 0;
}

The above is the detailed content of How do function pointers work in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn