Reputation: 1267
Here's the code:
#include<iostream>
using namespace std;
typedef struct ptrs
{
int (*addptr)(int a, int b);
}mems;
int add(int a, int b)
{
int result = a+b;
return result;
}
int main()
{
mems ptrtest;
ptrtest.addptr = &add;
int c = (*ptrtest.addptr)(3,4);
//int c = ptrtest.addptr(3,4);
cout << c << endl;
return 0;
}
if I replace the code int c = (*ptrtest.addptr)(3,4); with it's next line(annotated now), the result will be the same, why is that?
Upvotes: 1
Views: 83
Reputation: 6031
C++ will automatically cast a function name to a function pointer (and vise versa) if doing so will create correct syntax.
Upvotes: 0
Reputation: 64308
Functions and function pointers can be used interchangeably, presumably for convenience. In particular, section 5.2.2 of the C++11 standard specifies that a function call can occur using a function or a pointer to a function.
Upvotes: 1
Reputation:
Of course, int c = (*ptrtest.addptr)(3,4);
is the base case. However, in C++ (and in C as well), if you use the call (()
) operator on a function pointer, it will do the "dereferencing" automatically. Just like when assigned to a variable of function pointer type, the name of a function decays into a function pointer, i. e.
int (*fptr)() = some_func;
is just as valid as
int (*fptr)() = &some_func;
albeit the type of func
is int ()(void)
.
Upvotes: 3