hacaoideas hacaoideas - 1 month ago 8
C++ Question

c++ function pointer evaluates to 1

I define a simple function pointer pointing to a function, and when i try to output it evaluate to 1. What is happening behind the scene? (I am on mac, compiling with c++11 g++ compiler)

#include <iostream>

int foo()
{
return 5;
}


int main(int argc, char const *argv[])
{
int (*fcptr)() = foo;

std::cout<< fcptr;
return 0;
}


Output is 1.

M.M M.M
Answer Source

There is no overload of operator<< which takes std::ostream and a function pointer. However, there is one that takes std::ostream and a bool, and there is implicit conversion from function pointers to bool.

So your code converts the function pointer to bool, which is defined as yielding true if it was not a null pointer; and then outputs true , which is defined as outputting 1 by default. You could do std::cout<< std::boolalpha << fcptr; to see true outputted.