Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are normal C-array indices signed while stl indices are unsigned?

Tags:

c++

c

indexing

stl

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?

like image 249
TwistedBlizzard Avatar asked Nov 18 '25 15:11

TwistedBlizzard


1 Answers

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.

like image 99
dbush Avatar answered Nov 21 '25 06:11

dbush