1

I understand why stl indices are unsigned, because you would never have a negative index. But for normal C arrays, the indices are signed. Why is this?

If there is a good reason for C array indices to be signed, why did they decide to make stl indices different?

TwistedBlizzard
  • 931
  • 2
  • 9
  • 1
    c array access simply performs some unchecked, untyped pointer arithmetic - resulting pointer is also unchecked – Neil Butterworth Oct 29 '22 at 23:59
  • 1
    [An earlier answer by me](https://stackoverflow.com/questions/47170740/c-negative-array-index/47170794#47170794) explaining how negative indexes work. And it works in both C and C++. – Some programmer dude Oct 30 '22 at 00:05
  • Ask the standards committee. – Jesper Juhl Oct 30 '22 at 00:07
  • 1
    C array element access is specified in terms of dereferencing the sum of a pointer and an integral value (e.g. `p[i]` and `*(p+i)` are equivalent) where the pointer MAY point into the middle of a valid range hence negative indices can be meaningful. Indexing for C++ standard containers is specified in terms of a range with the first element (of the container) always at index zero with no preceding elements (and `v[i]` and `*(v+i)` are not equivalent if `v` is a standard container - in fact `*(v+i)` is a diagnosable error)- so negative indices are meaningless, and indices must be non-negative. – Peter Oct 30 '22 at 05:55

1 Answers1

9

Array indexing in C is really just a pointer offset. x[y] is exactly the same as *(x + y). That allows you to do things like this:

int a[3] = { 1, 2, 3 };
int *p = a;                   /* p points to a[0]  */
printf("p[1]=%d\n", p[1]);    /* prints 2          */
p += 2;                       /* p points to a[2]  */
printf("p[-1]=%d\n", p[-1]);  /* prints 2          */

Which is why negative array indexing is allowed.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Plus, even if not everydays, sometimes you really use negative index in totally legit and readable code. (I mean, it is not just for IOCC contest) – chrslg Oct 30 '22 at 00:02
  • also, in your third statement out putting p[-200] will probably print ... something or seg fault or whatever – Neil Butterworth Oct 30 '22 at 00:04