The same result

Hello Everybody, Im new here and im learning c++ from the e-book here.

while im reading the pointers chapter i had a problem that i get the same result from this 2 codes
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 (*func) (int,int))
{
    int r;
    r=(*func) (x,y);
    return r;
}

int main ()
{
    int i;
    int (*minus) (int,int)=subtraction;

    i=operation(10,5,minus);

    cout << i;
    return 0;
}


if i change this part of code
r=(*func) (x,y);

to this
r=(func) (x,y);

i get the same result

what's the difference between them? and the final result is the same?

THANKS
There is no difference. You can use a function pointer just as if it was a normal function.
r = func(x,y);
It's how it worked in C so C++ did the same to not break backward compatibility with C.
Last edited on
Thanks got it
so this is the c way
r=func (x,y);

and this is the c++ way

r=(*func) (x,y);

the c way seems easier
I think both ways works in C. (*func)(x,y); is similar to how you have to use operator* on normal pointers. func(x,y); is allowed because it's more convenient to use. For normal pointers they can't do the same thing and allow operator* to be left out because that would lead to ambiguities.
Last edited on
Sorry I am not helping you out with your problem, in fact I have one of my own after viewing this code.

1
2
3
4
5
6
int operation (int x , int y , int (*func) (int,int))
{
    int r;
    r=(*func) (x,y);
    return r;
}


what's this int(*func)(int, int) ? Are you passing a function as an argument to another function? Is that possible? :O
Why? And how? And what's the significance of this?
A pointer to function, from C++ point of view, is a functor (just like a pointer to an element of an array is a random access iterator)

Any functor can be invoked with operator(), no matter if it is a pointer to function, reference to function, std::function, std::plus, bind expression, closure object, or whatever. r = func(x,y) is the most logically-consistent C++ way.

But if you'd like to dereference that pointer to get a function lvalue and call operator() on that, you can do (*func)(x, y) just as well, it just won't be generic: you would have to change that code if you switch to std::function for example.

As for C vs C++
in C, operator() only works on pointers to functions, and any function name used in a function call expression is first implicitly converted to pointer and then invoked. f() is really (&f)() <- little-known trivia
In C++, operator() is defined for lvalues/references to functions and for pointers to functions separately
Last edited on
Topic archived. No new replies allowed.