Function Pointer in C

Level 5175 keystrokes

Declares a function pointer op, points it first at add and then at sub, and calls it the same way both times. op(10, 5) prints 15 with add and 5 with sub.

C code

// Two functions with the same signature, int (int, int); add returns a + b
1int add(int a, int b) { return a + b; }
// sub returns a - b
2int sub(int a, int b) { return a - b; }
3
// Declares op as a pointer to a function taking two ints and returning int
4int (*op)(int, int);
// Points op at add; the function name gives its address
5op = add;
// Calls add through the pointer: 10 + 5 prints 15
6printf("%d\n", op(10, 5));
// Reassigns op to sub at run time
7op = sub;
// The same call now runs sub: 10 - 5 prints 5
8printf("%d\n", op(10, 5));

Output

15
5
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
  • ,× 7
  • ;× 7
  • "× 4
  • {× 2
  • }× 2
  • \× 2
  • %× 2
  • =× 2

More C examples at level 5

← C typing practice