In the book, "Understanding and Using C Pointers" by Richard Reese it says on page 85,
int vector[5] = {1, 2, 3, 4, 5};
The code generated by
vector[i]
is different from the code generated by*(vector+i)
. The notationvector[i]
generates machine code that starts at location vector , movesi
positions from this location, and uses its content. The notation*(vector+i)
generates machine code that starts at locationvector
, addsi
to the address, and then uses the contents at that address. While the result is the same, the generated machine code is different. This difference is rarely of significance to most programmers.
You can see the excerpt here. What does this passage mean? In what context would any compiler generate different code for those two? Is there a difference between "move" from base, and "add" to base? I was unable to get this to work on GCC -- generating different machine code.
I think what the original text may be referring to is some optimizations which some compiler may or may not perform.
Example:
vs.
In the first case, an optimizing compiler may detect that the array
vector
is iterated over element by element and thus generate something likeIt might even be able to use the target CPU's pointer post-increment instructions where available.
For the second case, it is "harder" for the compiler to see that the address that's calculated via some "arbitrary" pointer arithmetics expression shows the same property of monotonically advancing a fixed amount in each iteration. It might thus not find the optimization and calculate
((void*)vector+i*sizeof(int))
in each iteration which uses an additional multiplication. In this case there's no (temporary) pointer that gets "moved" but only a temporary address re-calculated.However, the statement probably does not universally hold for all C compilers in all versions.
Update:
I checked the above example. It appears that without optimizations enabled at least gcc-8.1 x86-64 generates more code (2 extra instructions) for the second (pointer-arithmethics) form than the first (array index).
See: https://godbolt.org/g/7DaPHG
However, with any optimizations turned on (
-O
...-O3
) the generated code is the same (length) for both.