As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]
?
I just find out this ugly syntax could be "useful", or at least very fun to play with when you want to deal with an array of indexes which refer to positions into the same array. It can replace nested square brackets and make the code more readable !
Of course, I'm quite sure that there is no use case for that in real code, but I found it interesting anyway :)
I know the question is answered, but I couldn't resist sharing this explanation.
I remember Principles of Compiler design, Let's assume
a
is anint
array and size ofint
is 2 bytes, & Base address fora
is 1000.How
a[5]
will work ->So,
Similarly when the c code is broken down into 3-address code,
5[a]
will become ->So basically both the statements are pointing to the same location in memory and hence,
a[5] = 5[a]
.This explanation is also the reason why negative indexes in arrays work in C.
i.e. if I access
a[-5]
it will give meIt will return me object at location 990.
Because array access is defined in terms of pointers.
a[i]
is defined to mean*(a + i)
, which is commutative.Nice question/answers.
Just want to point out that C pointers and arrays are not the same, although in this case the difference is not essential.
Consider the following declarations:
In a.out, the symbol a is at an address that's the beginning of the array, and symbol p is at an address where a pointer is stored, and the value of the pointer at that memory location is the beginning of the array.
Not an answer, but just some food for thought. If class is having overloaded index/subscript operator, the expression
0[x]
will not work:Since we dont have access to int class, this cannot be done:
pointer types
1) pointer to data
2) const pointer to data
3) const pointer to const data
and the arrays are type of (2) from our list
When you define an array at a time one address is initialize in that pointer
As we know that we can't change or modify const value in our program cause it's throws an ERROR at compile time
The major difference I found is...
We can re-initialize the pointer by an address but not the same case with an array.
======
and back to your question...
a[5] is nothing but *(a + 5)
you can understand easily by
a - containing address (people call it as base address) just like an (2) type of pointer in our list
[] - that operator can be replaceable with pointer * .
so finally...