Printing function pointer passed as a parameter results in '1' printed on the screen

后端 未结 2 553
情话喂你
情话喂你 2021-01-17 04:42

I\'ve been experimenting with function pointers and found the behavior of the following program rather misterious:

void foo(int(*p)())
{ std::cout << p         


        
相关标签:
2条回答
  • 2021-01-17 05:11
    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.

    0 讨论(0)
  • 2021-01-17 05:18

    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;
    
    0 讨论(0)
提交回复
热议问题