I know it would be very bad coding-style, but the following code runs perfectly on my machine. But is the behavior well defined? Portable?
int main() { int *p = new int[3]; int *q = &p[2]; q[-1] = 41; std::cout << p[1]; delete[] p; }
This is well defined, both syntactically and semantically.
[expr.sub]/1 (N3337):
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
.
So your expression is the same as *(q-1) = 41;
, so is syntactically valid.
[expr.add]/5 (N3337)
When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression.
Since q
points to an element of an array object of a valid size for your integral expression, it is semantically valid.
Yes, it is well defined. Built-in operator[]
is defined in terms of pointer arithmetic. This:
p[N]
where p
is a pointer and N
is an integer, is equivalent to this:
*(p + N)
An interesting upshot of this is that this:
N[p]
is also equivalent, because addition is commutative.
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