C/C++ Function Pointer
Introduction
Function pointers are used to pass functions as arguments to other functions in C and C++. The usages are universal in C and C++.
In this blog post, I would like to briefly cover the usages of function pointers.
Examples
To define a function pointer, we have to declare its type. The type of function pointer has the following signature.
1 | T0 (*f)(T1, T2, T3, ...) |
where f
is the function pointer, T0
is the function output type, T1
, T2
, T3
, etc, represents the type for argument 1, argument 2, and argument 3, etc.
When calling the function using function pointer, (*f)
is just equivalent to f
because the function name is just the function address.
1 |
|
To compile the program, please run the following command in the terminal.
1 | $ g++ function_ptr.cpp -o function_ptr -std=c++11 |
Conclusions
Just memorize the function pointer signature and in most of the scenarios we would not make mistake.
C/C++ Function Pointer