Sample Video Frame
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 normal function declaration:
int callme(int a, int b)
- Wrap the function name with the pointer syntax:
int (*callme)(int a, int b)
- Change the name to the pointer name:
int (*compare_cb)(int a, int b)
The key thing to remember is, when you're done with this, the variable name for the pointer is called compare_cb and you use it just like it's a function. This is similar to how pointers to arrays can be used just like the arrays they point to. Pointers to functions can be used like the functions they point to but with a different name.
Register for Learn C the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.