function pointer print

#include 
#include 

void test()
{
}

int main()
{
  std::cout << test << std::endl;
  std::cout << &test << std::endl;
  std::cout << (void*)test << std::endl;
  printf("%p\n", test);
  printf("%llx\n", test);
  return 0;
}

output

1
1
0x4008b6
0x4008b6
4008b6

第三行對應 ostream & operator <<( ostream &, const void * ); 故輸出function address 但第一行與第二行出現1的原因是因為 cout 找不到直接對應的method 開始透過standard conversions找可以對應的method standard conversion可以參考c++03 standard 4. Standard conversions

找到了 boolean (function pointer被轉成boolean) 所以輸出1
參考:
https://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout

4.12 Boolean conversions [conv.bool]
An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of
type bool. A zero value, null pointer value, or null member pointer value is converted to false; any
other value is converted to true.

This entry was posted in C++ Language. Bookmark the permalink.

Leave a Reply