Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
XML
#include<iostream>
#include<conio.h>
using namespace std;

void main()
{
    int x[]={1,2,3};

    if(x[1]==1[x])
    {
        cout<<"Welcome"<<endl;
    }
    getch();

}

what is the difference between { x[1] , 1[x]}, and what is mean every one ???
Posted
Updated 2-Aug-12 20:55pm
v2
Comments
Sergey Alexandrovich Kryukov 17-Oct-12 15:51pm    
Incorrect question!
--SA

It is the same to compiler, because the compiler always will expand the array reference as *(x + 1) and *(1 + x), pointer arithmetic. But not so clear to programmers
 
Share this answer
 
Comments
Anderso0on 3-Aug-12 3:12am    
Please explain this more
hbprotoss 3-Aug-12 3:20am    
C/C++ compiler will expand something in the form of the array reference "array[index]" to more straight form *(array + index). And here + is pointer arithmetic.
You can try to replace 'array' and 'index' with x and 1 in you expression.
Let's see what is written in the standard,
here: http://www.open-std.org/jtc1/sc22/wg21/docs/wp/html/oct97/expr.html[^]
Please see the section #5.2.1 Subscripting

"A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type "pointer to T" and the other shall have enumeration or integral type. The result is an lvalue of type "T." The type "T" shall be a com-pletely-defined object type.3) The expression E1[E2] is identical (by definition) to *((E1)+(E2)). [Note: see _expr.unary_ and _expr.add_ for details of * and + and _dcl.array_ for details of arrays. ]"

So, arr[5] is the same as *(arr + 5) == *(5 + arr) == 5[arr].
Using the transitivity of addition (meaning that A+B == B+A) we can
get some pretty ugly, but valid, syntax when indexing into arrays:

So arr[i] == *(arr + i) then we apply the transitivity rule on the left hand giving *(i + arr) and then go back to the array-form gives i[arr].

So given array arr then 5[arr] will give the third element in arr.
And then we replace the 'i' with a variable and we get something like this:
C++
int main()
{
 int arr[3] = {1, 2, 3};
 for (int i = 0; i < 3; ++i)
 {
  std::cout << i[arr];
 }
 return 0;
}
 
Share this answer
 
No difference, see, for instance comp.lang.c FAQ list · Question 6.11[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900