int* p = 0;
int* q = &*p;
Is this undefined behavior or not? I browsed some related questions, but this specific aspect didn't show up.
See Question&Answers more detail:osint* p = 0;
int* q = &*p;
Is this undefined behavior or not? I browsed some related questions, but this specific aspect didn't show up.
See Question&Answers more detail:osThe answer to this question is: it depends which language standard you are following :-).
In C90 and C++, this is not valid because you perform indirection on the null pointer (by doing *p
), and doing so results in undefined behavior.
However, in C99, this is valid, well-formed, and well-defined. In C99, if the operand of the unary-&
was obtained as the result of applying the unary-*
or by performing subscripting ([]
), then neither the &
nor the *
or []
is applied. For example:
int* p = 0;
int* q = &*p; // In C99, this is equivalent to int* q = p;
Likewise,
int* p = 0;
int* q = &p[0]; // In C99, this is equivalent to int* q = p + 0;
From C99 §6.5.3.2/3:
If the operand [of the unary
&
operator] is the result of a unary*
operator, neither that operator nor the&
operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.Similarly, if the operand is the result of a
[]
operator, neither the&
operator nor the unary*
that is implied by the[]
is evaluated and the result is as if the&
operator were removed and the[]
operator were changed to a+
operator.
(and its footnote, #84):
Thus,
&*E
is equivalent toE
(even ifE
is a null pointer)