I know that a function pointer stores the address of a function.
int fun(int x){
//return something
}
int (pfun*)(int)=&fun;
int main(){
std::cout << &fun << "\n"; // this print out 1
std::cout << fun << "\n" ; // this print out 1
std::cout << &pfun << "\n"; // this print out 0x0022ff40
std::cout << pfun << "\n" ; // this print out 1
}
So my questions are :
1) if the fun() doesn’t even have an address how can pfun does point to fun().
2) for example in dynamic binding when I use a pointer function at runtime. does the compiler change pfun value to a real pointer like 0X….. so that at runtime will know which function to call since the names doesn’t existe after compilation?
The expressions
funand&funhave the same meaning:&funwhich is equivalent to the value stored inpfun, so it is no wonder that the three of them yield the same output.&pfunis the address of the pointer, which is the address of the variable.Now the question is why
1… well, the answer is that there is no overloadedoperator<<that takes anstd::ostreamand a function pointer, so the compiler tries to find the best match among the existing overloads which happens to bebool(a function pointer is implicitly convertible tobool). The function pointer will be converted tofalseonly if the function pointer is null, which is not the case. Thetruevalue is finally printed as1(you can check this by doing:std::cout << std::boolalpha << funwhich will printtrue).If you want to obtain the actual address of the function (in this process) you can force the cast to a void pointer and print the result. This might not be technically correct, but it will give you a number different than
1… Note that the value might differ in different runs and basically has no meaning at all.