logoalt Hacker News

kevin_thibedeauyesterday at 8:01 PM2 repliesview on HN

There are (rare) times when you want negative array indices. C lets you index in both directions from a pointer to the middle of an array. That's why array indexing is signed in C. Some libc ctypes lookup tables do this. For sizing there is no strong case for negatives other than to shoehorn them into signed operations.


Replies

CodeArtisantoday at 9:19 AM

>That's why array indexing is signed in C

C23 updated the definition of the [] operator to disallow negative subscripts with array type. I think you have to explicitly convert the array to a pointer type now.

    int a[2];
    a[-1]; // not ok
    (&a[0])[-1] // ok
C23: https://cstd.eisie.net/c2y.html#6.5.3.2

C11: https://port70.net/~nsz/c/c11/n1570.html#6.5.2.1

throwaway894345yesterday at 8:07 PM

That’s interesting but seems pretty dangerous. How do you know you aren’t going to decrement off the front of the array? Keeping the pointer to the first element in the array and using offsets seems safer for humans and I don’t think the computer would care.

show 2 replies