4 ms·
Actually, array indices do make sense as negative. For example, you might want an array going from a[-500] to a[700], without having to adjust the index all th
by cgore 13y ago
Actually, array indices do make sense as negative. For example, you might want an array going from a[-500] to a[700], without having to adjust the index all the time. It is much nicer if the array does it for you. Fortran lets you change the starting index if I remember correctly.
Most commonly you'll actually want to go positive, and have an array going from a[1970] to a[2013] or something similar.
- frenchy 13y agoPerhaps, though from a language design standpoint I think that adds unnecessary complexity. Either way, we're talking about C here, and in that context signed integers don't make sense as array indexes.
- dllthomas 13y agoThe fact that we're talking about C doesn't really make a difference, if you genuinely desire negative indices: int array[FOO]; int *shifted_array = array + FOO/2;
- cgore 13y agoThat's actually a nice trick. I just hope the compiler doesn't complain about it. I'll have to try that sometime. EDIT: just tried it. The following works: #include <stdio.h> int main(void) { int array[100]; int *shifted_array = array - 1980; for (int i = 0; i < 100; i++) array[i] = i; for (int j = 1980; j < 2014; j++) printf("shifted_array[%d] = %d\n", j, shifted_array[j]); return 0; }
- dllthomas 13y agoYeah, there's a couple cases where this kind if thing cleans things up; use it with caution though. More amusing, but less useful outside the IOCCC: The C subscripting operator performs an basically syntactic transformation, turning a[i] into (*(a + i)). This means that, counter-intuitively (if you're thinking of [] as a lookup) the construct i[a] works too because plus is commutative.