Hacker News new | ask | show | jobs
by habibur 1611 days ago
Read only top half of the article.

Would like to add that at least in plain C, doing var[index] doesn't invoke any checked() or unchecked() access function call. It's rather compiled into assembly instructions to calculate the address where the data is expected and load it into memory in one or two lines.

2 comments

You’re taking C extremely literally, and compilers are not required to do this (for example, if the array is being iterated sequentially, multiple loads may be done at once). Similarly, in Rust a function call is not necessarily going to actually compile to a function call: it is expected that the access compiles down to something very close to what C would do. The syntax is an abstraction, rather than a normative designation to the compiler for how it should generate code.
Which is, incidentally, why you can also write `index[var]`. `[]` is really just a convenience for `*(var + index)`. In fact that's exactly how the standard defines it (or at least defined it as of C11, I've not checked more recent versions):

> 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))).