3 ms·
How would this work for unaligned accesses - which index would very likely be. A neat way to look at things nevertheless, thanks.
by sifar 7y ago
How would this work for unaligned accesses - which index would very likely be. A neat way to look at things nevertheless, thanks.
- cosarara 7y agoThe alignment doesn't matter. `index` is not an offset in bytes, it's just an index, a number. The position in memory of the variable also doesn't matter as it is not used, only the value. `index[arr]` means `*(index + arr)`. Which is exactly the same thing as arr[index], no matter how you look at it. The type of arr is taken into account for pointer arithmetic. Whatever works with `arr[index]` will also work with `index[arr]`. You can also use a constant, for example `2[arr]`. Damn I hate HN formatting.
- sifar 7y agoyes, I realized this after asking the question :).I must admit I never thought it in this way. Thinking more about this, this might fail if the compiler uses post-incrementing load/stores which update the pointer addresses too. Or will it not use them if I am using index[arr] ? Lets say the load/store updates the pointer too. So after first execution, ptr will index+arr in both cases, but during the next iteration , the former will be ptr[index] while the latter will be ptr[arr].
- tom_mellior 7y agoUnless you try hard to provoke one, there is no unaligned access. Adding a pointer and an integer in C always displaces the pointer by elements, not by bytes. So if p is a pointer to some type T and is aligned, then p + 1 will be aligned as well. You need to cast to another pointer type, do arithmetic on that, then cast back to produce an unaligned access.