Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is negative index for operator[] well defined?

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; } 
like image 384
user1235183 Avatar asked Aug 18 '15 10:08

user1235183


2 Answers

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.

like image 175
TartanLlama Avatar answered Sep 20 '22 19:09

TartanLlama


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.

like image 45
Benjamin Lindley Avatar answered Sep 18 '22 19:09

Benjamin Lindley