CodeBlanks Logo Icon CodeBlanks

Summary - Function pointers

  • C course
  • Intermediate
  • Lesson 29/116
  • 5 min

Combine qsort, callback and dispatch table to write a command handler.

Designing a command handler

In this summary you'll combine qsort, callback and dispatch table concepts to write a command handler. The command handler calls the matching function by command name.

The structure: define add, sub and mul functions. Collect them in a function pointer array. Then call each in turn and print the result. Thanks to the dispatch table, adding a new command is just appending an element to the array; the calling logic stays the same. This is the core pattern of real command-line apps and interpreters.

Practice Write a command handler

Write int add(int a, int b), int sub(int a, int b) and int mul(int a, int b). Declare a function pointer array with int (*ops[3])(int, int) = {add, sub, mul};. Call all three commands: printf("%d\n", ops[0](3, 4));, printf("%d\n", ops[1](10, 7)); and printf("%d\n", ops[2](2, 5));.

Starter code

main.c
#include <stdio.h>

// Write add, sub, mul
// Declare ops function pointer array
// Call all three commands in main

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int mul(int a, int b) { return a * b; }

int main(void) {
    int (*ops[3])(int, int) = {add, sub, mul};
    printf("%d\n", ops[0](3, 4));
    printf("%d\n", ops[1](10, 7));
    printf("%d\n", ops[2](2, 5));
    return 0;
}

Expected output

7
3
10

Summary

In this group you learned function pointers in depth. You saw the definition, two call forms, use with qsort, the callback pattern and the dispatch table.

You combined these to write a command handler. qsort callback, forEach callback and dispatch table; all three are different uses of function pointers. These patterns are common in real-world C code: event handling, sorting, command processing and interpreters. In the next groups these foundations will be used on more complex data structures and systems programming.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What's the best use case for a dispatch table?

  • Math calculations
  • Memory allocation
  • Command handlers Correct answer
  • String concatenation

Explanation: Command handlers are the best use case for dispatch tables.

2 Match the concepts to use

Term Meaning
qsort Comparator callback
forEach Element callback
ops[0](...) Dispatch call
int (*fp)(int) Pointer type

All lessons in Intermediate