can't under stand a code

i can't understand how does this code work

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
  // pointer to functions
#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;
}
Because everything sits in memory (code and data alike) everything has an address.

your function "operation()" takes an address of some code as its 3rd parameter. the code at the address is expected to be a function that takes 2 ints as parameters and returns an int result.

line 21 declares a new address for some code (just like the parameter declaration at line 11, the variable is called minus and it is assigned to point to the code at "subtraction"

line 23 calls operation" passing the address of the code you want to use (addition)

line 24 calls "operation" passing the address of the code you want to use (minus), however there isn't a routine called "minus" its just a variable that holds the address of "subtraction" assigned at line 21.

so line 24 is actually calling "n=operation(20,m,subtraction)"

ok?


ok and thx alot
Topic archived. No new replies allowed.