0

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.

user6646922
  • 497
  • 1
  • 6
  • 15
  • 2
    `cout` always prints function pointers as `1` unless they are null. That's because its `<<` has no special overload for them, and closest overload (the one you get) is for `bool`. Cast the pointer to something like `uintptr_t` to see its real value. – HolyBlackCat Jan 28 '18 at 17:24

2 Answers2

6
std::cout << p << std::endl;

here an overload of operator<< which accepts a bool is picked up:

basic_ostream& operator<<( bool value );

As p is not null, then 1 is printed.

If you need to print an actual address, then the cast is necessary, as others mention.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
1

Your function pointer is cast to a bool which is true, or 1 without std::boolalpha.

If you want to see the address you can cast it:

std::cout << static_cast<void*>(p) << std::endl;
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122