by pyre · 15y ago · 0 comments
a[5]
evaluates to something like: *(a + (sizeof(a) * 5))
so shouldn't 5[a]
evaluate to *(5 + (sizeof(5) * a))
Those don't seem equivalent, unless I'm missing something.It only wouldn't work in very weakly typed languages like ... assembler?
Separately:
e + p where e : integer-type and p : pointer-type
p + e where e : integer-type and p : pointer-type
are evaluated roughly as: (pointer-type)(e*sizeof(*p) + (size_t)p)
(pointer-type)((size_t)p + e*sizeof(*p))
but these are very rough translations, because we're wandering into implementation-defined territory (substitute uintptr_t for size_t as desired etc).The type analysis on the addition is reminiscent of e.g. promoting integers to floats:
i + f where i : integer-type and f : float-type
f + i where i : integer-type and f : float-type
correspondingly: (float-type)i float-type::+ f
f float-type::+ (float-type)i
The '+' built-in is overloaded in C.