Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
Is the possibility of both array[index] and index[array] a compiler feature or a language feature. How is the second one possible?
Join Stack Overflow to learn, share knowledge, and build your career.
Is the possibility of both array[index] and index[array] a compiler feature or a language feature. How is the second one possible? |
|||||
marked as duplicate by Konrad Rudolph, Matthew Flaschen, paxdiablo, Mehrdad Afshari, aJ. May 25 '09 at 11:26This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. |
|||||
|
|||||
|
The compiler will turn
into
With the normal syntax it would turn
into
and thus you see that both expressions evaluate to the same value. This holds for both C and C++. |
|||||||||||||
|
|
As Matthew Wilson discusses in Imperfect C++, this can be used to enforce type safety in C++, by preventing use of
There's more to this, for dealing with pointers, but that requires some additional template smarts. Check out the implementation of edit: some of the commenters suggest that the implementation does not reject pointers. It does (as well as user-defined types), as illustrated by the following program. You can verify this by uncommented lines 16 and 18. (I just did this on Mac/GCC4, and it rejects both forms).
|
|||||||||||||||||||||
|
|
From the earliest days of C, the expression
Update: You can probably safely ignore the bit above between the |
|||||||||||||||||||||
|
|
In C and C++ (with array being a pointer or array) it is a language feature: pointer arithmetic. The operation a[b] where either a or b is a pointer is converted into pointer arithmetic: *(a + b). With addition being symetrical, reordering does not change meaning. Now, there are differences for non-pointers. In fact given a type A with overloaded operator[], then a[4] is a valid method call (will call A::operator ) but the opposite will not even compile. |
|||
|
|