Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why is a[i] == i[a] in C/C++ arrays?
In C programming, there's an interesting feature where array subscript notation a[i] can also be written as i[a]. This happens because of how C internally handles array indexing through pointer arithmetic.
Syntax
a[i] == i[a] // Both expressions are equivalent
How It Works
In C, E1[E2] is defined as (*((E1) + (E2))). The compiler performs pointer arithmetic internally to access array elements. Because the binary + operator is commutative, a[i] becomes *(a + i), and i[a] becomes *(i + a). Since addition is commutative, both expressions evaluate to the same memory location.
Example
Here's a demonstration showing both notations produce identical results −
#include <stdio.h>
int main() {
int array[] = {10, 20, 30, 40, 50, 60, 70};
printf("Using standard notation:\n");
printf("array[0] = %d\n", array[0]);
printf("array[3] = %d\n", array[3]);
printf("array[5] = %d\n", array[5]);
printf("\nUsing reverse notation:\n");
printf("0[array] = %d\n", 0[array]);
printf("3[array] = %d\n", 3[array]);
printf("5[array] = %d\n", 5[array]);
printf("\nBoth are equivalent:\n");
printf("array[2] == 2[array]: %s\n", (array[2] == 2[array]) ? "True" : "False");
return 0;
}
Using standard notation: array[0] = 10 array[3] = 40 array[5] = 60 Using reverse notation: 0[array] = 10 3[array] = 40 5[array] = 60 Both are equivalent: array[2] == 2[array]: True
Pointer Arithmetic Explanation
The equivalence works because −
-
a[i]translates to*(a + i) -
i[a]translates to*(i + a) - Since
(a + i) == (i + a), both expressions access the same memory address
Key Points
- This feature exists due to C's pointer arithmetic implementation
- While syntactically valid,
i[a]notation should be avoided for code readability - The standard
a[i]notation is preferred in production code - This works with both arrays and pointers in C
Conclusion
The equivalence between a[i] and i[a] demonstrates C's underlying pointer arithmetic. While interesting academically, always use the conventional a[i] notation for better code clarity and maintainability.
