C++ Pointer Arithmetic: A Corporate Investigation
Description
This meme uses the popular 'Corporate needs you to find the differences between this picture and this picture' format from the TV show 'The Office.' In the top panel, the character Pam holds up two images. The left one displays the code 'Array[i]', the standard syntax for accessing an array element. The right one shows 'i[Array]', a highly unconventional but valid syntax. In the bottom panel, Pam's face is obscured by the C++ logo, and she declares, 'They're the same picture.' The humor is rooted in a deep-cut feature of C and C++. Due to how pointer arithmetic is implemented, `Array[i]` is interpreted by the compiler as `*(Array + i)`. Since addition is commutative, this is identical to `*(i + Array)`, which can be expressed as `i[Array]`. Thus, both expressions are functionally the same. This esoteric language quirk is often used as a trivia question to test a developer's understanding of the language's low-level mechanics
Comments
7Comment deleted
Using `i[Array]` in production code is the professional equivalent of putting a mint in your urinal: technically it works, but it's going to make everyone deeply uncomfortable
I slip an occasional i[Array] into the C codebase - if the PR gets rubber-stamped, I know the reviewers are parsing with their eyes, not their pointers
After 20 years of explaining to junior devs why i[Array] works in C, you realize the real bug is that you still remember the segment:offset addressing from your 8086 days and occasionally dream in assembly
Ah yes, the classic C interview gotcha that separates those who've actually read K&R from those who just use arrays like normal people. Sure, 'i[Array]' works because array subscripting is just pointer arithmetic in disguise - *(Array + i) equals *(i + Array) thanks to commutative addition - but if I ever see this in production code, we're having a very different conversation about maintainability. It's the programming equivalent of technically-correct-but-please-don't: like using trigraphs or #define true false. Yes, you've demonstrated deep knowledge of C's memory model. No, your code reviewers won't thank you for flexing it
C defines a[b] as *(a + b), so i[arr] compiles; the compiler approves, but your readability SLO just breached
In C, i[arr] == arr[i] - pointer addition commutes; bounds are a social construct
Corporate wants diffs; C's preprocessor says they're identical after *(Array + i)