I've been experimenting with function pointers and found the behavior of the following program rather misterious:
void foo(int(*p)())
{ std::cout << p << std::endl; }
int alwaysReturns6()
{ return 6; }
int main()
{
foo(alwaysReturns6);
return 0;
}
The above code prints the number '1' on the screen.
I know I should access the function pointer like this: p()
(and then 6 gets printed), but I still don't get what the plain p
or *p
means when used in the foo
function.
here an overload of
operator<<
which accepts abool
is picked up:As
p
is not null, then1
is printed.If you need to print an actual address, then the cast is necessary, as others mention.
Your function pointer is cast to a
bool
which istrue
, or1
withoutstd::boolalpha
.If you want to see the address you can cast it: