I've asked a question here about whether taking the address of a function forces the compilation of said function specifically with regard to Substitution-Failure-Is-Not-An-Error. The most direct answer to this can be found here:
Informally, an object is odr-used if its address is taken, or a reference is bound to it, and a function is odr-used if a function call to it is made or its address is taken. If an object or a function is odr-used, its definition must exist somewhere in the program; a violation of that is a link-time error.
But all the compilers I've tested show this as perfectly doable:
void foo(int);
auto bar = &foo;
This isn't legal is it? But if not, why is it building?
From [basic.def.odr]:
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 tostd::max()
orstd::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.http://ideone.com/97Eo6Z