3 ms·
Trying to intuit how a language works tends to be problematic. To understand this operation, you need to look it up in the spec: http://www.open-std.org/jtc1/s
by biot 15y ago
Trying to intuit how a language works tends to be problematic. To understand this operation, you need to look it up in the spec: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf
Section 6.5.2.1 "Array Subscripting" states in item (2) under "Semantics" on page 70:
A postfix expression followed by an expression in square brackets []
is a subscripted designation of an element of an array object. The
definition of the subscript operator [] is that E1[E2] is identical
to (*((E1)+(E2))). Because of the conversion rules that apply to
the binary + operator, if E1 is an array object (equivalently, a
pointer to the initial element of an array object) and E2 is an
integer, E1[E2] designates the E2-th element of E1 (counting from
zero).
In other words:
a[5] is equal to (*((a)+(5)))
5[a] is equal to (*((5)+(a)))
So what are the rules for E1+E2? Refer to section 6.5.6 "Additive Operators", item (8) under "Semantics" on page 83:
When an expression that has integer type is added to or subtracted
from a pointer, the result has the type of the pointer operand. If
the pointer operand points to an element of an array object, and
the array is large enough, the result points to an element offset
from the original element such that the difference of the subscripts
of the resulting and original array elements equals the integer
expression. In other words, if the expression P points to the i-th
element of an array object, the expressions (P)+N (equivalently,
N+(P)) and (P)-N (where N has the value n) point to, respectively,
the i+n-th and i−n-th elements of the array object, provided they
exist.
In other words, if (P)+N is equal to N+(P), you need only substitute "a" for "P" and "5" for "N" and that proves a[5] == 5[a]. If I've missed something, corrections are welcomed.
- deleted 15y ago[deleted]
- Someone 15y agoGiven that these are separate sections in the C spec, would &12[5] == 17 (ignoring OS memory protection)?
- biot 15y agoThe constraints section of 6.5.2.1 requires that one expression be a pointer. If you cast one of those numbers to a byte pointer with its address at the numerical location in memory, I don't see why it wouldn't result in a pointer to memory location 0x00000017. Give it a shot!