Function Pointer in C

Level 4183 keystrokes

Demonstrates function pointers to call different functions dynamically.

C code

// Function that adds two integers
1int add(int a, int b) { return a + b; }
// Function that subtracts two integers
2int sub(int a, int b) { return a - b; }
3
// Declare function pointer: returns int, takes two ints
4int (*op)(int, int);
// Point to add (a function name converts to its address)
5op = add;
// Call add through pointer: 5 + 3 = 8
6printf("Add: %d\n", op(5, 3));
// Now point to sub
7op = sub;
// Call sub through pointer: 5 - 3 = 2
8printf("Sub: %d\n", op(5, 3));

Output

Add: 8
Sub: 2
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 4

← C typing practice