Trying to understand this program?

I'm trying to understand the following program which is given in the tutorials section of this website, under "Pointers to functions".

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;
}


Can someone give me a simple walk-through/trace of whats going on here? Is minus simply pointing to the function 'subtraction'?

How does the third parameter of 'operation' function work?
Last edited on
Is minus simply pointing to the function 'subtraction'?
Yes.
How does the third parameter of 'operation' function work?
It is a pointer to function taking two integers and returning integer. In your program pointer to subtraction (which takes two integers and returns integer) is passed.
What about line 22? m = operation (7, 5, addition);

Is 'addition' also a pointer to function? It was never declared a pointer like 'minus' was, so im confused about that. If its NOT a pointer to function, how is it passed to the third parameter in 'operation'?
A function can be implicitely converted to pointer to it. So an address of addition function is passed.

Also pointer to function can be implicitely dereferenced, so line 13 can be also written as
g = functocall(x,y);
Last edited on
Topic archived. No new replies allowed.