Why in the C language is array[6] equal to 6[array]?


Note: Question I saw on the SO in English , but I thought it was interesting to put it here (because we still don't have many C questions):

Why in the C language, this code prints "true"?

#include <stdio.h>

int main(void) {
    int reais[10];
    for(int i=0; i<10; ++i) reais[i] = i;
    int num = reais[6];
    int num2 = 6[reais];
    if(num == num2) printf("verdadeiro"); else printf("falso");
    return 0;

Nota: Compilei isso com C99, ele NÃO COMPILA no C89 (porque não pode declarar variável dentro do for() )

Quem quiser pode copiar e colar isso no ideone.com para ver compilar e rodar.


Referenciando o standard do C: Array subscripting

One of the expressions shall have type “pointer to complete object type“, the other
expression shall have integer type, and the result has type “type“.

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

O relevante é que ao escrever a[b], um dos valores deve ser um ponteiro (ou uma array que decaia a um ponteiro) e outro deve ser um tipo integral. Não é especificado nenhuma restrição sobre qual deve ser o que. O segundo ponto é que a[b] é equivalente a *(a+b). Assim temos:

a[b] = *(a+b) = *(b+a) = b[a]

The same can also be applied to literal strings, as they are const char[] :

char M = 4["Ola Mundo"];

While this syntax is perfectly valid and legal, it's not good practice to access arrays by reversing the operands like this. Reading is quite unintuitive and there are no advantages.

Scroll to Top