0

Normally we access an array element in this manner: arrayName[elementID]. But even we use like elementID[arrayName] it compiles and does not cause any errors in runtime. Isn't it logically wrong? Can anyone explain me this. I'm new to C++. Thank you in advance for any help!

#include<iostream>
using namespace std;

int main()
{
    int arr[4] = {2, 4, 5, 7};
    cout << arr[2] << endl; //this is the correct way to use it 
    cout << 2[arr] << endl; //this gives the same result and does not cause any errors
    return 0;
}
Almo
  • 15,538
  • 13
  • 67
  • 95
James Noah
  • 11
  • 1
  • `[]`s are (approximately) syntactic sugar for pointer addition with a dereference, and addition is commutative. – dlf Sep 26 '14 at 15:20
  • 1
    When asking other people to read your code, please put spaces around operators and after commas. It makes it easier for us to help. I already edited it. – Almo Sep 26 '14 at 15:22

1 Answers1

3

The following are equivalent:

a[b] == *(a + b) == *(b + a) == b[a]

It really doesn't matter which one you use, so long as it's readable and it conveys the intent of the programmer.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 2
    I would ask another question - is this a feature or bug in C++ caused by backwards compatibility with C (personally I think `2[array]` must be a compile error), but I think it's offtopic for SO... – Anton Savin Sep 26 '14 at 15:27