I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such
You can think of a function pointer as being the address of the first instruction in that function's machine code. Any pointer can be treated as a bool
: 0 is false and everything else is true. As you observed, when cast to void *
and given as an argument to the stream insertion operator (<<
), the address is printed. (Viewed strictly, casting a pointer-to-function to void *
is undefined.)
Without the cast, the story is a little complex. For matching overloaded functions ("overload resolution"), a C++ compiler gathers a set of candidate functions and from these candidates selects the "best viable" one, using implicit conversions if necessary. The wrinkle is the matching rules form a partial order, so multiple best-viable matches cause an ambiguity error.
In order of preference, the standard conversions (and of course there also user-defined and ellipsis conversions, not detailed) are
int
to float
)The last category includes boolean conversions, and any pointer type may be converted to bool
: 0 (or NULL
) is false
and everything else is true
. The latter shows up as 1
when passed to the stream insertion operator.
To get 0
instead, change your initialization to
pf = 0;
Remember that initializing a pointer with a zero-valued constant expression yields the null pointer.