function pointers

I know function pointers but what is the importance of them?
They allow you to call functions without having to know the name of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using std::cout;
using std::endl;

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

int sub( int a, int b )
{ return a - b; }

int mul( int a, int b )
{ return a * b; }

int div( int a, int b )
{ return a / b; }

int mod( int a, int b )
{ return a % b; }

void do_it( int a, int b, int (*func)( int, int ) )
{
    cout << " a = " << a << ", b = " << b 
           << ", result = " << func( a, b ) << endl;
}

int main() {
    do_it( 5, 4, add );
    do_it( 5, 4, sub );
    do_it( 5, 4, mul );
    do_it( 5, 4, div );
    do_it( 5, 4, mod );
}


A simple example to demonstrate the concept. The do_it() function now does 5 different things ... depending on the function you pass to it.

Thanks
In other words, the function call can be changed at runtime.
Very nice example to explain it - but doesn't the iostream already have some pre-built functions called: add, sub, div and mul? Not dissing your code at all its a very nice explanation - just encase people copy and paste your example ;)
Actually, I'm pretty sure those are there by default...don't need to include iostream at all to use + - / * etc.
Topic archived. No new replies allowed.