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.

Press + to interact
#include <stdio.h>
typedef void(*styleFunc)(int);
void style1(int elem)
{
printf("%d ", elem);
}
void style2(int elem)
{
printf("[%d] ", elem);
}
void style3(int elem)
{
printf("%d", elem);
}
void style4(int elem)
{
printf("%d,", elem);
}
int printArray(int arr[], int n, styleFunc printWithStyle)
{
printf("arr: ");
for(int i = 0; i < n; i++)
{
printWithStyle(arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, 5, style1);
printArray(arr, 5, style2);
printArray(arr, 5, style3);
printArray(arr, 5, style4);
return 0;
}

Let’s analyze the code:

  • typedef void(*styleFunc)(int); is the type of the style function (line 3). A style function does not return anything and takes the element to print as an argument of type int.
  • We then define four style functions (styleX) in lines 5, 10, 15 and 20. Every function prints its element
...