0Pricing
C Academy · Lesson

Passing Functions

Callbacks as arguments.

Functions as Arguments

Because a function pointer is just a value, you can pass a function into another function. The received function is called a callback.

This lets one routine customize part of its behavior.

#include <stdio.h>

int apply(int x, int (*f)(int)) {
    return f(x);
}

int square(int x) { return x * x; }

int main(void) {
    printf("%d\n", apply(6, square));
    return 0;
}

The Callback Parameter

The callback parameter is declared just like a function pointer variable. Inside, you call it like any function.

#include <stdio.h>

void run_twice(void (*action)(void)) {
    action();
    action();
}

void beep(void) { printf("beep\n"); }

int main(void) {
    run_twice(beep);
    return 0;
}

All lessons in this course

  1. Declaring Function Pointers
  2. Passing Functions
  3. qsort with Comparators
  4. Function Pointer Tables
← Back to C Academy