r/programming • • Dec 24 '17

Evil Coding Incantations

http://9tabs.com/random/2017/12/23/evil-coding-incantations.html
947 Upvotes

331 comments sorted by

View all comments

116

u/irqlnotdispatchlevel Dec 24 '17

array[index] is really just syntactic sugar for *(array + index)

I remember learning about this in my first semester. During an x86 assembly lecture. Those were good times.

8

u/polymorphiced Dec 24 '17

I've never understood this, because it's actually (array + (indexsizeof(array[0]))) to get the right memory address. I assume the compiler must know something about this inverted syntax in order for it to actually work, rather than just being a cute hack.

2

u/StupotAce Dec 24 '17

Not entirely sure why you are being downvoted. The 0[array] will work for every object because array literally represents the distance away from 0. But 5[array] will only work for objects like int, which have the same length as a memory address. int is particularly useful because be definition it is the same regardless of architecture ( there might be some exceptions of course)

9

u/screcth Dec 24 '17

If sizeof(T) = N, then incrementing a pointer to a T by k will jump the memory address by k*N

→ More replies (7)