It's been fairly well-asked here if negative indices are allowed in C, but I'm curious of there is any performance downside to using this technique frequently. For example, does it break the compiler's ability to use the base+offset indexing on some hardware platform somewhere, or confuse the optimizer, etc.
I ask because I have a lot of decoding routines with the signature of
decode_something(char *buffer, int buffer_size, int bit_position) {
...
if (((bit_position + need_bits) >> 3) < buffer_size) {
x= buffer[bit_position >> 3] ...
bit_position += need_bits;
...
}
and I realized I can greatly simplify all that code if I use a pointer to the end of the buffer:
decode_something(char *buf_limit, int bits_remaining) {
...
if (need_bits <= bits_remaining) {
x= buf_limit[ -((bits_remaining+7) >> 3) ];
bits_remaining -= need_bits;
...
}
(well, actually this example doesn't show how it gets "much" simpler, but you can extrapolate to all the cases where calling this function or saving the parse state only require two variables instead of three.)
Now I'm considering using this pattern throughout an entire library, but I wanted to know if there's some reason not to do that.