C++ exchanging the array name and index value when accessing the array element

An intriguing case when accessing an array element is exchanging the array name and index value in the syntax still yield the correct value.Consider the code below.

LInk : C++ accessing an array

int iar[]={ 00, 10, 100 , 1000 }

/*** index and array name are exchanged ***/
cout<< 1[iar] << endl // work fine prints 10
 << 3[iar] ; //work fine prints 1000

for( size_t i=0 , size=sizeof(iar)/sizeof(int) ; i++)
{
cout<< i[iar] << endl; //work fine
}

Why does the above syntax: 1[iar] work? To understand why this form is valid we will need to look deeper into the Compiler way of executing an array.

First thing to note is the compiler does not know what is array,the whole array syntax form is only accustom to us,we the programmer.When we ask the compiler to print the third element by providing the expression-iarr[2],the compiler does not understand it.The compiler evaluate the expression by turning it into it’s own understandable from.

So what compiler does is it will turn it into a pointer expression.And the expression will look something like this *(iarr+2).The meaning of this expression is “give the value present in the second position from the address of ‘iarr’” or it can be interpreted as “give the value present at the address ‘iarr+2*(sizeof(int))‘“;the size of the data type is also required to calculate the address.Consider the code below.

cout<< iarr[2] << ” ” << *(iarr +2 ) << endl ; //the output are the same
<< iarr[3] << ” ” << *(iarr+3) << endl ; //the output are the same

cout<< (int)iarr << ” ” << (int)(iarr+2) ;  //The difference is 8 bytes

‘iarr’ points to 0 position , (iarr+1) points to 1st position and (iarr+2) points to second position so when iarr[2] or *(iarr+2) is evaluated the value at (iarr+2) is printed out, simple isn’t?.

So now you know what whenever programmer asked for the value iarr[2] the compiler converts the expression iarr[2] to the form *(iarr+2) and simply outputs whatever value is present at (iarr+2) address.

 

Now going back to the discussion why exchanging the index and the array name will still yield the same value.In providing the expression ‘2[iarr]’,the compiler is liable to convert it into a pointer form.Obviously the compiler will now be viewing the expression ‘2[iarr]’ as *( 2 + iarr ) .Now *( 2 + iarr ) can be written as *(iarr + 2 ),which is in fact the form obtain when the array is accessed using the standard form – iarr[2].So in this case also the compiler will yield the third element of the array.Although the expression used may be different in the interface level but underneath if the interpretation is the same the compiler will certainly comply;this is also why they say, “Looks does not matter,beauty is what lies underneath!”.I bet we can’t say no to that saying ,can we?




Leave a Reply

Your email address will not be published. Required fields are marked *