0
#include <stdio.h>

int main(){
    int x[5]={1,2,3,4,5};
    for (int i=0;i<5;i++){
        printf("%d\n",i[x]);
    }
}

I have written this small c code.i created array named x and returning all elements of array with the help of for loop but in for loop i assigned i[x] in printf() function to get array all values but the name of array is x and it perfectly running.Does i[x] and x[i] are same meaning in C.

machine_1
  • 4,266
  • 2
  • 21
  • 42
Maninder Singh
  • 425
  • 6
  • 14
  • 4
    Does this answer your question? [With arrays, why is it the case that a\[5\] == 5\[a\]?](https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a) – Karsten Koop Apr 16 '20 at 10:18

1 Answers1

0

According to the C Standard (6.5.2.1 Array subscripting)

2 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).

So this expression x[i] is calculated like *( x + i ) that is the same as *( i + x ) and as i[x].

Pay attention to that the loop can be also rewritten the following way

int x[]={1,2,3,4,5};
const size_t N = sizeof( x ) / sizeof( *x );

for ( size_t i = 0; i < N; )
    printf( "%d\n", i++[x] );

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    int x[] = { 1, 2, 3, 4, 5 };
    const size_t N = sizeof( x ) / sizeof( *x );

    for ( size_t i = 0; i < N; )
        printf( "%d\n", i++[x] );

    return 0;
}

Its output is

1
2
3
4
5
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335