0

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

Can anyone explain me why for any array the expression c a[7] == 7[a] is true.

is there any case that it can be false

I have seen in wiki that x[i] is a syntactic sugar for *(x+i) and this is equal to *(i+x) and this is i[x], but I can not understand this properly.

Community
  • 1
  • 1
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 1
    It's not a duplicate. That question is about 5, this one is about 7. :) – Barmar Dec 19 '12 at 08:04
  • 1
    Before searching on SO, consider checking the excellent [comp.lang.c FAQ](http://c-faq.com/aryptr/joke.html). – Lundin Dec 19 '12 at 09:44

3 Answers3

7
  • a[7] is equivalent to *(a + 7).
  • Similarly 7[a] is equivalent to *(7 + a).

This gives the same result because adding an integer to a pointer is a commutative operation.


is there any case that it can be false

The short answer is no. For simple pointer arithmetic it will always be true.

The long answer is that to find a counterexample you would have to use a hack. One way you could do it is to use a macro:

#include <stdio.h>

#define a 1+s

int main(void) {
    char s[] = "1q2w3e4r5t6y";
    int x = a[7];
    int y = 7[a];
    printf("%c %c\n", x, y);
    return 0;
}

Result:

s 5

The result is different because after the macro expansion the expressions become different: 1+(s[7]) versus 7[1+s].

See it online: ideone

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

a[7] gets translated to *(a+7) & 7[a] gets translated to *(7+a), which refer to same location & thus same data.

anishsane
  • 20,270
  • 5
  • 40
  • 73
0

I have seen in wiki that x[i] is a syntactic sugar for *(x+i) and this is equal to *(i+x) and this is i[x], but I can not understand this properly.

It's Simple pointer arithmetic and addition is commutative. (so I don't think there should be any problem to understand)

see this...

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

a+7 is 7+a because addition operation is commutative.

Hence a[7] == 7[a] , proved

Omkant
  • 9,018
  • 8
  • 39
  • 59