Passing Functions as Arguments

Learn to pass functions as arguments to other functions.

Introduction

We can pass function pointers as arguments to functions. It’s a great way of dynamically changing the code’s behavior at runtime, and allows us to easily introduce new functionality in the future.

Let’s illustrate with a simple example. Let’s say we want to create a function to print an array. We already did this in a previous chapter, but now we want to be able to customize how the output looks.

We could create multiple functions, but then we’d have to repeat the for loop iterating over the array in every one of them. We should find a way of doing it that helps us avoid duplicate code.

Using function pointers

We can use function pointers to solve the problem of duplicate code! The printArray function will receive a style function that controls the style to print the element. Then, if we want more styles, we just have to create a different style function and pass it to the printArray function.

Get hands-on with 1200+ tech skills courses.