I found the example below here. Clearly the comment in the snippet was wrong as the variable S::x
is odr-used by the expression &S::x
.
struct S { static const int x = 1; };
void f() { &S::x; } // discarded-value expression does not odr-use S::x
int main(){
f();
}
See live example
I understand the compiler doesn't need to emit such an error because [basic.def.odr]/10 says "no diagnostic required". But why doesn't the linker emit an error about the undefined variable S::x
, as it does in the code below?
#include<iostream>
struct S { static const int x = 1; } s;
int main() {
std::cout << &s.x << '\n';
}
See live example.
But why doesn't the linker emit an error about the undefined variable S::x, as it does in the code below?
Because it is simply optimized out! An expression which result is never used and has no side effect will simply be ignored. And what was ignored must not be linked in. There is simply no code which reference the variable, also if the address of it was taken but then is not used.
As seen in your wandbox example, the compiler emits the correct diagnostic: "expression result unused".
Code which is not in use will not result later in linker errors ;)
Your second example uses the value ( address of var ) and so there is a need to evaluate the expression. That emits code to the linker where the symbol of the address can not be found anywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With