4 ms·
What I think takes the cake is this: array[index] == index[array] Not that you would actually use this, but it gave me a lot of insight into how addressing
by jallmann 16y ago
What I think takes the cake is this:
array[index] == index[array]
Not that you would actually use this, but it gave me a lot of insight into how addressing and stuff works inside the compiler. Also from this example, there's the implicit suggestion that an array can be treated as a pointer. So that leads into pointer arithmetic which can be very useful.
- dgallagher 16y agoThe same as above, only using Pointer Arithmetic instead of Array Subscripting: *(array + index) == *(index + array) Further broken down: *(&array[0] + index) == *(index + &array[0])
- jallmann 16y agoYep. And if teaching that to a bunch of middle or high schoolers, I would add that pointer arith works in increments of sizeof(array[0]) bytes. If you're not careful about operator precedence in moderately complicated expressions, that could come back to bite you.
- brl 16y agoYou didn't really spell out why this trick works: array[index] == *(array + index) == *(index + array) == index[array]
- alan-crowe 16y agoarray + index == index + array needs justification One expects the generic + in a+i to get expanded to raw addition .+. and raw multiplication .x. with s the size of elements of the array a .+. s .x. i One expects index + array to throw a type error because index is just a number and doesn't have an element size. So I'm guessing that the real reason that the trick works is that generic + has three methods with signatures int + int array + int int + array
- philwelch 16y agoThis is a fantastic way to show younger or beginning programmers to think beyond what the code is supposed to denote and consider how it works in reality--in other words, the hacker's perspective. A naive programmer takes array[index] at face value. The hacker gets the idea that array[index] is just *(array + index) deeply enough to make a perverse joke out of it.