Why arr[1] and 1[arr] is same for array ? How to overload [] for class to work both these ways ? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
+ 1

Why arr[1] and 1[arr] is same for array ? How to overload [] for class to work both these ways ?

Why arr[1] and 1[arr] is same for array ? How to overload [] for class to work both these ways ?

7th Apr 2023, 7:50 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 2
In C++, an array name is a pointer to the first element of the array. So,Ā arr[1]Ā andĀ 1[arr]Ā are equivalent expressions because they both evaluate toĀ *(arr + 1). This is because addition is commutative in C++, soĀ arr + 1Ā andĀ 1 + arrĀ are equivalent expressions.
7th Apr 2023, 10:42 PM
Aliul Nadab
Aliul Nadab - avatar
+ 1
the compiler converts the array operation into pointers before accessing the array elements, which means: arr[i] == *(arr + i); therefore arr[1] will evaluate to ā†’ *(arr+1), and 1[arr] will evaluate to ā†’ *(1 + arr) which is the same as *(arr + 1) and from elementary school math we know those are equal (addition is commutative). NOTE: donā€™t use this syntax in real code. this only works for the built-in subscript operator.
7th Apr 2023, 10:42 PM
MO ELomari