CodeBlanks Logo Icon CodeBlanks

typedef and function pointer

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

Learn function pointer types with typedef.

typedef and function pointer

Function pointer syntax is long and hard to read. With typedef you give it a short, meaningful name.

Example: typedef int (*BinOp)(int, int);. This names a pointer to a function taking two ints and returning int as BinOp. From then on you write BinOp op = add; instead of the hard-to-read int (*op)(int, int) = add;. typedef with function pointers is the standard way to express dispatch tables and callbacks cleanly. The type name reflects its purpose; the code documents itself.

Using BinOp

After defining BinOp, you can assign any function with a matching signature. The call is simply op(a, b).

Example: define int add(int a, int b) { return a + b; }. Then assign with BinOp op = add;. Call with printf("%d\n", op(3, 4));; the result is 7. The pointer holds the function's address; the call is made directly. This is the clean way to choose which function to call at run time. The same BinOp type can represent addition, subtraction, multiplication, and more.

Practice Write a typedef fp program

Define typedef int (*BinOp)(int, int);. Write int add(int a, int b) that returns a + b. In main assign BinOp op = add;. Call with printf("%d\n", op(3, 4));.

Starter code

main.c
#include <stdio.h>

// Define BinOp type with typedef
// Write the add function
// Assign add to op in main and call

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>

typedef int (*BinOp)(int, int);

int add(int a, int b) {
    return a + b;
}

int main(void) {
    BinOp op = add;
    printf("%d\n", op(3, 4));
    return 0;
}

Expected output

7

Questions and answers

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

1 Match the typedef fp parts

Term Meaning
typedef Naming
(*BinOp) Pointer name
(int, int) Parameter list
int Return type

2 When is BinOp op = add; valid?

  • When add takes two ints and returns int Correct answer
  • When add takes any parameters
  • When add is defined inside main
  • When add is declared static

Explanation: BinOp takes two ints and returns int; add must match that signature.

3 Complete the BinOp assignment

Question
BinOp op = ____;
Answer
BinOp op = add;

Explanation: BinOp op = add; assigns add to the function pointer.

All lessons in Intermediate