-3

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

Someone told me this... I didn't believe them at first but it does work. If x and y do not change throughout the code, why does this work:

int x [5] = { 0,1,2,3,4};
int y = 3;

if(x[y] == y[x]){
    cout << "Why..." << endl;
}

How does x array's value in index y is = the x index's value's in array y? But there was no y array.

Community
  • 1
  • 1
Gabriel
  • 3,039
  • 6
  • 34
  • 44

3 Answers3

6

It is always true (for normal operator==)

a[i]  --> *(a+i) --> *(i+a) --> i[a]

since int is intrinsic and has commutative operator==, this will always be true

sehe
  • 374,641
  • 47
  • 450
  • 633
3

Because all of the following are same:

x[y] == y[x] == *(x+y) == *(y+x)
Alok Save
  • 202,538
  • 53
  • 430
  • 533
2

Because x[y] is just another way to say *(x + y), and that is the same as *(y + x).

Paul Manta
  • 30,618
  • 31
  • 128
  • 208