int main() {
const int x = 0;
int* y = x; // line 3
int* z = x+x; // line 4
}
Quoth the standard (C++11 §4.10/1)
A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type
std::nullptr_t
. A null pointer constant can be converted to a pointer type; ...
There are four possibilities:
Line 4 is OK, but line 3 isn't. This is because
x
andx+x
are both constant expressions that evaluate to 0, but onlyx+x
is a prvalue. It appears that gcc takes this interpretation (live demo)Lines 3 and 4 are both OK. Although
x
is an lvalue, the lvalue-to-rvalue conversion is applied, giving a prvalue constant expression equal to 0. The clang on my system (clang-3.0) accepts both lines 3 and 4.Lines 3 and 4 are both not OK. clang-3.4 errors on both lines (live demo).
Line 3 is OK, but line 4 isn't. (Included for the sake of completeness even though no compiler I tried exhibits this behaviour.)
Who is right? Does it depend on which version of the standard we are considering?