Function Pointers - Everything you need to know!
Function pointers are pointers that point to code. When these are dereferenced, the fetched data is treated like instructions and the CPU executes them.
Consider typedef void (*function_ptr_t)(void);
to be the function pointer type. Because of the typedef
keyword, the function_ptr_t
is treated like a new type. As per this definition, the pointer is to return nothing and takes no parameters. Try the following code -
The output should be - Hello, World!
. What happened here was, the fptr
variable was of the type function_ptr_t
which is a function pointer type. The fptr
was pointing to the address where the code of random_function
was saved. When we dereference the pointer with the syntax - fptr()
the address is loaded into the program counter and the CPU fetches the instructions to execute.
Hopefully, you are convinced how a function pointer works. Now let's look at some more details and use cases.
C Pointers: Secrets every Embedded Engineer must know!
This course will enable you to think and use pointers like a professional senior/staff engineer in ~6Hrs - Ways to
- Visualize
- Think,
- Reason, and
- Design
Using pointers as experts do. The course takes a detailed hands-on approach, explaining the code, the theory, and the underlying system details one should consider when dealing with pointers in C. It is full of graphics, annotation and hands on demo that the students can try along in GitHub Codespaces.
More Details: https://inpyjama.com/c-pointers-course/
The Syntax
The general syntax is return type (* function pointer name)(parameter list)
. The function/code being pointed to should have the same return type and parameters. For example, the snippets below add
has the same return types and parameter list as fn
.
Without typedef
Using typedef
is not strictly required, if we decide not to use it, the function pointer variable declaration will be as in the code below. Notice how the syntax is long and hard to read.
With typedef
typedef
will create a new type for us which happens to be called fn
. We can use fn
just like any other data type, as used to define fpt
. This as you see, is more readable.