On 14/02/2011 14:40, James Kanze wrote:
A compiler can optimize indexing into a local array as direct memory
read of the stack (i.e. offsetting the stack pointer) without performing
any pointer arithmetic at all.
Please cite the part of the Standard which says that indexing into an
array *requires* converting the array into a pointer. Although the
array/pointer *equivalence* exists it is not a *requirement* that such
*equivalence* always be utilized by a compiler (implementation) as far
as I can tell (I could be wrong; I am not familiar with the entire
Standard).
§5.2.1:
A postfix expression followed by an expression in square
brackets is a postfix expression. One of the expressions
shall have the type “pointer to T” and the other shall
have enumeration or integral type. The result is an
lvalue of type “T.” The type “T” shall be
a completely-defined object type. The expression E1[E2]
is identical (by definition) to *((E1)+(E2)).
It's the definition of the [] operator. (Note that this allows
things like 1["abc"].)
After that, of course, there is the "as if" rule, which says
that the compiler can do pretty much anything it wants, as long
as the "observable behavior" of the program doesn't change. The
standard really doesn't impose much on the generated code.
In the case of user defined [], all bets are off, and the
language imposes no relationship between it and any other
operator. Most pre-standard array or vector classes I've seen
do define it as an index operator (and do not define any
associated pointer operations). In this regard, std::vector and
std::array are a bit special: although they do define [] as an
indexing operator, they also support pointers (and iterators)
into the array, and that pointer arithmetic on those pointers
works as it does with built-in arrays.