-1
int test[] = {1,2,3,4};

printf("%i",3[test]);

How is this the same as test[3]? I know that array variable can be used as a pointer to the first element and that can be used to refer to or point to the other variables in the array but how is this statement correct? 3 is not an array variable here.

Nalin
  • 3
  • 4

2 Answers2

2

The idea is test[3] is actually considered as *(test+3) which is same as *(3+test) because of around + the 3 and test commute. As a result 3[test] is also possible. It doesn't matter if you write it *(3+test) or *(test+3) or test[3] and 3[test].

From 6.5.2.1p2 C11 standard

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

E1[E2] is indeed *((E1)+(E2)) and we know binary addition is commutative. So we can say that it is same as *((E2)+(E1)) so can't we write it as E2[E1]. Yes we can and that's legal.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • I do not exactly understand this commuting thing. Can you please explain it a little more? – Nalin Feb 12 '18 at 05:27
  • 1
    @Nalin Did you sleep in math class? Addition is commutative, meaning that order does not matter. `1+5` is equal to `5+1`. When dealing with pointer arithmetic (arithmetic when a pointer is involved) the same applies. – Pablo Feb 12 '18 at 05:34
  • @Pablo Yes I know that. I was just confused about the use of []. – Nalin Feb 12 '18 at 07:38
0

When you use %i or %d it specifies a signed decimal integer. Then the value assigned for that integer is denoted by 3[test]. Therefore here %i denotes the value of the 4th element of the array(because array pointer starts with 0)

Sameera Sampath
  • 626
  • 1
  • 11
  • 20