Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array Access using Index : why is a[2] equivalent to 2[a]?

Status
Not open for further replies.

GSSV

Programmer
May 29, 2003
2
US
Why is it possible to access an nth element of an array using index as a[n] as well as n[a]?

Eg:
int a[4]={1,2,3,4];
The second element can be accessed both as a[2] (the normal way!!) and also as 2[a]

Array elements referenced by way of index is resolved by pointer arithmetic. But this still doesnot explain how references such as 2[a] is handled!!
 
An array subscript is expanded by the compiler like this:

a[2];

*(a + 2);

or

2[a];

*(2 + a);

Since addition is commutative, both expressions are equivalent.
 
Technical note - integral promotion also applies here. When adding an integral value directly to a pointer, the integer is actually added to the size of the pointer automatically.

*(2 + a);

Could be stated like so:

long *a;

*(( 2 * sizeof(long) ) + a);

This is one of the cool things about 'C', but the fact that this integer promotion is automagic leaves many a confused programmer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top