Why is Taking the Address of a Function That is Declared Only Working?

半世苍凉 提交于 2019-12-02 09:15:39

From [basic.def.odr]:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.

foo is odr-used, but doesn't have a definition (presumably - otherwise the question is moot). The program is ill-formed, but since no diagnostic is required, it's valid to compile.

Typically, it's the linker that catches the lack of definition - not the compiler, since the definition could easily appear in a different translation unit. The canonical example being trying to pass a static const int which lacks a definition into a call to std::max() or std::min().

Your example is working because the address is never used, so the linker never searches for the symbol.

If you try to print bar, the linking fails.

void foo(int);
auto bar = &foo;
cout << (void*) bar;

http://ideone.com/97Eo6Z

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