typedef for Function Pointers in C

Level 4235 keystrokes

Uses typedef to simplify function pointer declaration and creates an array of functions.

C code

// Operation is now the name of the type "pointer to a function (int, int) -> int"
1typedef int (*Operation)(int, int);
2
// Functions matching the Operation signature
3int multiply(int a, int b) { return a * b; }
4int divide(int a, int b) { return a / b; }
5
// Array of function pointers using the typedef
6Operation ops[] = {multiply, divide};
// Call multiply through array: 12 * 3 = 36
7printf("Mul: %d\n", ops[0](12, 3));
// Call divide through the array: integer division 12 / 3 = 4
8printf("Div: %d\n", ops[1](12, 3));

Output

Mul: 36
Div: 4
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ,× 8
  • (× 8
  • )× 8
  • ;× 6
  • "× 4
  • [× 3
  • ]× 3
  • {× 3
  • }× 3
  • :× 2

More C examples at level 4

← C typing practice