Function pointer in C++

Level 4218 keystrokes

Declares a pointer to functions taking two ints and returning an int, points it first at add and then at multiply, and calls it each time.

C++ code

// Two functions with the same signature int(int, int)
1int add(int a, int b) { return a + b; }
2int multiply(int a, int b) { return a * b; }
3
// operation is a pointer to a function taking (int, int) and returning int
4int (*operation)(int, int);
// A function name converts to its address, so no & is needed
5operation = add;
// Calls add(5, 3): prints 8
6cout << operation(5, 3) << endl;
// Point the same variable at another function
7operation = multiply;
// Calls multiply(5, 3): prints 15
8cout << operation(5, 3) << endl;

Output

8
15
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
  • ;× 7
  • (× 6
  • )× 6
  • ,× 5
  • {× 2
  • }× 2
  • *× 2
  • =× 2
  • +× 1

More C++ examples at level 4

← C++ typing practice