Reputation: 1738
#include <iostream>
using namespace std;
const int BUFSIZE = 1 << 20;
char padded_buffer[64 + BUFSIZE + 64];
char* buffer = padded_buffer + 64;
int main()
{
buffer[-1] = '?';
// is that always equivalent to padded_buffer[63] = '?' ?
cout << padded_buffer[63] << "\n";
return 0;
}
I have a piece of code like above. Basically, I need to "fence" the two side of my array for some reasons.
But I wonder if the syntax above is safe? I know that negative indexing is generally undefined behavior, but what about this case?
Upvotes: 9
Views: 605
Reputation: 122595
From https://eel.is/c++draft/expr.sub#2:
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
, except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.
And pointer arithmetics is defined as long as you only reach pointers to elements within the same array.
There is no undefined behavior. buffer[-1]
is just *(padded_buffer + 64 -1)
.
It is somewhat opinion based, but buffer[-1]
looks odd. Imho it obfuscates the fact that buffer
is not an array but a pointer to an element in the middle of the actual array. If you want to assign something to the 63th element of the array padded_buffer
then just do that: padded_buffer[63] = '?';
.
In a comment I suggested to wrap the array in a custom type with overloaded operator[]
, but this will not solve the issue of weird looking x[-1]
. Perhaps I'd rather make the index transformation directly visible in the calling code, to have padded_array[ transform_index(-1) ]
.
Upvotes: 10