richard.g
richard.g

Reputation: 3765

pointers to functions in c++

It's kinda hard to name a title for my question, so plz pardon me for this ambiguous title.

Function names are regarded as the addresses of functions, so we can assign them to function pointers.

...
void fun(){cout<<"fun called";}  
int main()
{
typedef void (*pf)();
pf p1 = fun;
//Then we can call p1()
p1();
...
}

This is of no problem. What puzzles me is that pf p2 = &fun; p2(); will do the exact same thing as p1 with no warnings or errors.

"fun" is the address of the function, so shouldn't &fun be the address of the address of the function? And when I assign &fun to p2, there should be a type inconsistency, I think. Why pf p2 = &fun is a legal assignment?

Upvotes: 2

Views: 117

Answers (2)

user529758
user529758

Reputation:

Function names are regarded as the addresses of functions

"fun" is the address of the function

Neither of these statements is correct. A function name is not a pointer but a function designator; it is only the case that it is - similarly to an array - implicitly converted to a pointer ("decays into a pointer") in some, but not all, contexts, for example, when assigned to an object of type pointer-to-function or when called.

This implicit conversion does not happen when the function is the argument of the unary & (address-of) operator, hence &function_name will be of type "pointer to function", and not "pointer-to-pointer-to-function".

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477610

No.

The id-expression formed by the name of a function decays to the function pointer, except in certain circumstances. One of those circumstances is when it is the operand of the address-of operator. In that case it does not decay, and the result of evaluating the address-of operator on the function name is the address of the function.

Upvotes: 6

Related Questions