When C++ Gets Weird: i[a] and the Power of Pointer Arithmetic

When you first learn arrays in C++, you’re taught that a[i]
accesses the i-th element of the array. Simple enough, right?
But what if I told you that writing i[a]
—yes, flipping the index and the array—also works?
This might seem like a typo, or even something that should crash your compiler. But surprisingly, it’s perfectly valid C++ and behaves exactly the same as a[i]
. Let's dig into why this works, what it means, and what it teaches us about how C++ handles arrays and pointers.
🔍 The Surprise in Code
Let’s look at a minimal example:
#include <iostream>
using namespace std;
int main() {
int a[] = {10, 20, 30, 40, 50};
cout << a[2] << endl; // Output: 30
cout << 2[a] << endl; // Output: 30 (!)
return 0;
}
let’s understand how!
What’s Actually Happening?
To understand this, you need to know what a[i]
really means in C++.
Under the Hood:
a[i] == *(a + i)
This is pointer arithmetic at work. When you write a[i]
, the compiler translates it into:
👉 “Go to the address a
, add i
to it, and get the value at that memory location.”
Since addition is commutative, a + i
is the same as i + a
.
So:
a[i] == *(a + i) == *(i + a) == i[a]
💡 This is why i[a]
works. It's just another way of writing *(a + i)
.
Is This Useful?
Realistically? Not really.
Nobody writes i[a]
in production code. It’s not readable, and it can confuse teammates (and your future self). But as a learning moment, it’s golden.
It proves that arrays are deeply tied to pointers in C++, and that array access is just syntactic sugar for pointer math.
Bonus: Modify Elements with i[a]
Here’s a fun twist—you can even assign through this form:
int a[] = {1, 2, 3};
2[a] = 99; // Same as a[2] = 99;
cout << a[2]; // Output: 99
Mind. Blown.
A Word of Caution
Just because something is legal in C++ doesn’t mean it’s a good idea.
i[a]
is clever and fun, but don’t use it in real code unless you want confused teammates and endless questions in code reviews. Use it as a teaching trick or a conversation starter in interviews.
Conclusion
C++ is full of quirks that make you pause and say, "Wait… what?"
The fact that a[i] == i[a]
is one such gem. It teaches us:
Arrays are closely related to pointers.
Array indexing is just syntactic sugar over pointer arithmetic.
C++ lets you peek behind the curtain if you dare.
So next time you want to impress (or confuse) your friends, just write i[a]
—and then explain why it works.
Final Thought:
Have your own favorite C++ trick or quirk? Share it in the comments or tweet it with the hashtag #CppMagic
!
Subscribe to my newsletter
Read articles from Vikram Shrivastav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
