O'Reilly logo

Learn C the Hard Way: A Clear & Direct Introduction To Modern C Programming by Zed A. Shaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required