Exercise 18. Pointers to Functions
Functions in C are actually just pointers to a spot in the program where some code exists. Just like you’ve been creating pointers to structs, strings, and arrays, you can point a pointer at a function, too. The main use for this is to pass callbacks to other functions, or to simulate classes and objects. In this exercise, we’ll do some callbacks, and in the next exercise, we’ll make a simple object system.
The format of a function pointer looks like this:
int (*POINTER_NAME)(int a, int b)
A way to remember how to write one is to do this:
• Write a normal function declaration: int callme(int a, int b)
• Wrap the function name with the pointer syntax: int (*callme)(int a, int b) ...
Get Learn C the Hard Way: A Clear & Direct Introduction To Modern C Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.