4

following code

a[10] == 10[a]

the result seems true in C-language

how C compiler sees both of them as the same ?

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57
  • Are you sure about this? Or you're asking only for accessing an element of the array, not defining one. – Kiril Kirov Feb 18 '13 at 09:46
  • 1
    [compile error](http://liveworkspace.org/code/33824t$0) – Karthik T Feb 18 '13 at 09:48
  • 1
    The answers already tell you why this is the case (because arrays degrade to pointers), but you should note that **10[a] is very bad practice** because it does not communicate intent, it is just syntax that confuses the readers of your code. It actually is objectively worse syntax because arithmetic on indices is more frequent than arithmetic on the array-base and a[2*x] is shorter than (2*x)[a]. – Bernd Elkemann Feb 18 '13 at 09:52
  • @eznme, instead of "confusing" i'd rather use the term "trolling" :) – kaspersky Feb 18 '13 at 09:55
  • @KarthikT: You have to declare the array in the usual form first. Then it is valid. In your example, you tried to declare the array which is invalid syntax. In C, both given expressions are equivalent (at least were in C90, not sure about newer revisions of the standard). `a[10]` will become `*(a+10)` and `10[a]` will become `*(10+a)`. – Axel Feb 18 '13 at 09:56
  • @Axel during accessing it is equivalent, that is known and has already been pointed out. However that is now how OP shows it, though he may mean it.. – Karthik T Feb 18 '13 at 09:57
  • What I see is an example of accesing. But the question was edited some minutes ago. I haven't seen the original question. Maybe that's why? – Axel Feb 18 '13 at 10:02
  • @Axel Yes, that's why, originally they were framed as declarations. – Daniel Fischer Feb 18 '13 at 10:10

2 Answers2

6

The compiler sees as follows:

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

Check this for a better explanation.

Community
  • 1
  • 1
kaspersky
  • 3,959
  • 4
  • 33
  • 50
2

a[10] means: "Start at memory address 10, add a to it and reference the resulting location" 10[a] means: "Start at memory address a, add 10 to it and reference the resulting location"

Since a + 10 is the same as 10 + a, both expressions will refer to the same memory location.

Kesty
  • 610
  • 9
  • 19