I have written the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
double funcA()
{
return 100.0;
}
int g(double (*pf)())
{
cout << (*pf)() << endl;
return 0;
}
int g2(double pf())
{
cout << pf() << endl;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
g(&funcA); // case I
g(funcA); // case II
g2(funcA); // case III
g2(&funcA); // case IV
return 0;
}
I have run the above code on VS2008 and each function call returns ‘100’.
Here is the question:
Q1> Is there any problem in the code?
Q2> It seems that C++ doesn’t make difference between *pf and pf. Is that correct?
Thank you
C++ does, in fact, make a distinction between the types
double()anddouble(*)(), but the difference is subtle. When you pass a function type as an argument to a function, the function-type automatically “degrades” to a function pointer. (This is similar, I suppose, to how an array type degrades to a pointer type when passed as a function argument.)However, a function type and a function-pointer type are still different types, according to the C++ type-system. Consider the following case:
This should fail to compile, since you cannot declare a function type as an automatic variable. (Remember, functions are not first-class objects in C++.) So the declaration
F func;is invalid. However, if we change ourmainfunction to instead instantiate the template using a function pointer, like so:…now it compiles.