user1235183 - 4 months ago 26

C++ Question

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;

}

Answer

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.