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

本秂侑毒 提交于 2020-01-21 10:20:17

问题


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

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

int alwaysReturns6()
{ return 6; }

int main()
{
    foo(alwaysReturns6);
    return 0;
}

The above code prints the number '1' on the screen.

I know I should access the function pointer like this: p() (and then 6 gets printed), but I still don't get what the plain p or *p means when used in the foo function.


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/48489196/printing-function-pointer-passed-as-a-parameter-results-in-1-printed-on-the-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!