Pointers to functions

I was reading the c++ tutorial on this site and made it to this part:

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
#include <iostream>
using namespace std;

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

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

int operation (int x, int y, int (*functocall)(int,int))
{
  int g;
  g = (*functocall)(x,y);
  return (g);
}

int main ()
{
  int m,n;
  int (*minus)(int,int) = subtraction;

  m = operation (7, 5, addition);
  n = operation (20, m, minus);
  cout <<n;
  return 0;
}


and I realized I could also do it this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

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

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

int operation (int x, int y, int (functiontocall)(int,int))
{
    int g;
    g = (functiontocall)(x,y);
    return (g);
}

int main ()
{
    int m,n;

    m = operation (7,5,addition);
    n = operation (20,m,subtraction);
    cout << n;
}


so why would anyone ever bother to make a pointer point to a function when they can do it this way? I don't really see the use in using pointers to call a function.
Last edited on
In any case a parameter declared as a function is implicitly converted to the function pointer. it is the same as with arrays. For example

void f( int a[10] );

is equivalent to

void f( int *p );
Last edited on
Topic archived. No new replies allowed.