I'm a newbie to C++, learning pointer of function recently, a little confused by usage of pointer of function;
I practiced the following code:
#include <iostream>
#include <sstream>
using namespace std;
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
int (*minus)(int,int)=subtraction;
cout<<minus(5,4);
return 0;
}
it works well; so,I try a little variation:
#include <iostream>
#include <sstream>
using namespace std;
int subtraction(int a,int b){
return a-b;
}
int main(int argc, const char * argv[])
{
int *minus(int,int)=subtraction;//only here different!
cout<<minus(5,4);
return 0;
}
I practiced it in Xcode on Mac,it give me Error:
Illegal initializer (only variables can be initialized)
but I think compiler can recognized the two is same,why must have a pair of parenthesizes?
In your original code
int (*minus)(int,int)=subtraction;
declares minus
as a function pointer that takes parameter int, int
and returns int
.
In your second code
int *minus(int,int)=subtraction;
declares minus
as a function that takes parameter int, int
and returns a pointer int *
.
You can use a function name(which is automatically converted to a function pointer) to initialize a function pointer, but you can't initialize a function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With