#include <iostream>
usingnamespace 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?
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.
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.
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