Why does code compile when you attempt to access a value in 0 as an array?

59 Views Asked by At

Let's say you have the code as follows:

float arr[] = {
    0.0f,
    1.0f,
    62.0f,
    400.0f
};

Then I print this out as follows:

printf("%lu\n", sizeof(0[arr]));

Why does it return 4, and what is happening here?

1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

From 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 0[arr] is equivalent to the expression arr[0].

The only difference is relative to how the subscript operator is defined in the C grammar.

It is defined like

postfix-expression [ expression ]

So for example

++i[arr] is not the same as arr[++i]. The first expression is equivalent to ++( i[arr] ). While this expression i++[arr] is equivalent to arr[i++].

Here is a demonstration program.

#include <stdio.h>

int main( void )
{
    int arr[] = { 10, 20 };
    size_t i = 0;

    printf( "++i[arr] = %d\n", ++i[arr] );

    i = 0;

    printf( "arr[++i] = %d\n", arr[++i] );
    
    putchar( '\n' );

    i = 0;
    arr[0] = 10;

    printf( "i++[arr] = %d\n", i++[arr] );

    i = 0;

    printf( "arr[i++] = %d\n", arr[i++] );
}

The program output is

++i[arr] = 11
arr[++i] = 20

i++[arr] = 10
arr[i++] = 10