Why is a[i] == i[a] in C/C++ arrays?

CC++Server Side ProgrammingProgramming

Here we will see one amazing trick in C or C++. The array subscript A[i] can also be written as i[a]. In C/C++ E1[E2] is defined as (*((E1) + (E2))). The compiler performs arithmetic internally to access the array elements. Because of the conversion of rules, that is applied to the binary + operator, if E1 is an array object, and E2 is an integer, then E1[[E2] signifies the E2th element in the E1 array. So A[B] can be defined as *(A + B), so B[A] = *(B + A). so they are basically the same thing.


 Live Demo

#include <iostream>
using namespace std;
int main() {
   int array[] = {1, 2, 3, 4, 5, 6, 7};
   cout << "array[5] is " << array[5] << endl;
   cout << "5[array] is " << 5[array];


array[5] is 6
5[array] is 6
Published on 03-Jan-2020 15:44:37