当您尝试将 0 中的值作为数组访问时,为什么代码会编译?

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

假设您有如下代码:

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

然后我打印如下:

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

为什么会 return 4,这里发生了什么?

来自 C 标准(6.5.2.1 数组下标)

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

所以这个表达式 0[arr] 等价于表达式 arr[0].

唯一的区别在于下标运算符在 C 语法中的定义方式。

定义如下

postfix-expression [ expression ]

例如

++i[arr]arr[++i] 不同。第一个表达式等效于 ++( i[arr] )。虽然此表达式 i++[arr] 等效于 arr[i++].

这是一个演示程序。

#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++] );
}

程序输出为

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

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