6

The following code outputs 1, but I expect it to output the address of the function add. What is going wrong?

#include <iostream>

int add(int x, int y) { return x + y; }

int main()
{
    int (*func_ptr)(int,int) = add;
    std::cout << "The address of function add() is: " << func_ptr << std::endl;
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Abdulvakaf K
  • 606
  • 1
  • 7
  • 16
  • The function pointer is implicitly cast to boolean. There was a similar question recently, – stefaanv Nov 08 '16 at 12:32
  • 3
    Possible duplicate of [How to print function pointers with cout?](http://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout) – stefaanv Nov 08 '16 at 12:34

2 Answers2

10

Function pointers aren't convertible to data pointers. You'd get a compiler error if you were to try and assign one to a void* variable. But they are implicitly convertible to bool!

That is why the bool overload for operator<< is chosen over the const void* one.

To force the overload you want, you'd need to use a very strong C++ cast, that will almost completely ignore the static type information.

#include <iostream>

int add(int x, int y) { return x + y; }

int main()
{
    int (*func_ptr)(int,int) = add;
    std::cout << "The address of function add() is: "
              << reinterpret_cast<void*>(func_ptr)
              << std::endl;
}

See live example at Compiler Explorer

Note that casting and treating function pointers as data pointers is only conditionally supported (from the C++ standard standpoint). Using it for anything other than casting back to the same function pointer will have an implementation specific outcome, that can very greatly among compilers.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
3

The overload used is

ostream& ostream::operator<< (bool val);

Which prints 1 as your function pointer is not null.

Jarod42
  • 203,559
  • 14
  • 181
  • 302