2

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.

hacaoideas
  • 105
  • 8
  • You probably forgot to invoke the function via the function pointer... Add `()` to invoke the function... if that's what you want. – WhiZTiM Aug 23 '17 at 02:51
  • Do you want the pointer value or to execute the pointed-to function and capture the return value? – genpfault Aug 23 '17 at 02:52
  • Hi I want to print the address of the function in memory space. – hacaoideas Aug 23 '17 at 02:58
  • 1
    cast it to `void*` – Retired Ninja Aug 23 '17 at 03:00
  • 1
    the reason You getting 1 is somehow g++ (tested under Centos 7, g++ 4.8.5) compiles Your code to call operator<< (bool) which gives not-NULL=true=1. You need to cast fcptr to int, void*, etc. to get actual function address. btw Your code gives correct address in MSVC. – NoAngel Aug 23 '17 at 03:11
  • this is definitely not a dupilicate of the marked question. this is some whacky compiler specific behavior. even cout << addressof(*fcptr) prints 1. prtinf("%p", fcptr) yields the correct result. – Josh Aug 23 '17 at 03:14
  • @Josh `printf("%p", fcptr);` is undefined behaviour , `%p` is only for `(void *)` argument – M.M Aug 23 '17 at 03:50
  • Have linked this question to one that both explains the output `1` and suggests how to output the function pointer in other ways, since OP indicated in comments that they wanted to do so – M.M Aug 23 '17 at 03:53
  • @M.M fair enough on undefined behavior. you'd be pretty hard pressed to find an example of a pointer that didn't print via %p on modern architecture i imagine. casting a function pointer to void* is undefined as well, no? anyway, for whatever reason, msvc chooses an appropriate << overload and prints the pointer. – Josh Aug 23 '17 at 04:12
  • @RetiredNinja such a cast is conditionally-supported (some compilers may not support it) – M.M Aug 23 '17 at 05:02

1 Answers1

5

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.

M.M
  • 138,810
  • 21
  • 208
  • 365