如 initramfs 所示,左手赋值中无名括号背后的机制是什么?

What's the mechanism behind nameless brackets in left hand assignment as seen in initramfs?

我在浏览 Linux 源代码时,在 initramfs 的第 400 行遇到了一段不熟悉的代码。我知道括号中的名称是 188 枚举中的状态。在我看来,这是一个默认数组设置函数指针(我可能是错的)。

我不明白括号的作用,示例用例是什么?我还发现等号令人困惑。此外,我想知道代码实现的模式是否有通用名称。

static __initdata int (*actions[])(void) = {
    [Start]     = do_start,
    [Collect]   = do_collect,
    [GotHeader] = do_header,
    [SkipIt]    = do_skip,
    [GotName]   = do_name,
    [CopyFile]  = do_copy,
    [GotSymlink]    = do_symlink,
    [Reset]     = do_reset,
};

侧面;对于 naive/general 的问题,我深表歉意,我正在努力扩展我对 C 的了解。我搜索了但找不到完整的英文源注释版本。

变量actions是一个数组,使用方括号[]用于标识符,即告诉编译器数组的索引是什么正在初始化。

来自 C11 规范 (§6.7.9/6):

If a designator has the form

[ constant-expression ]

then the current object (defined below) shall have array type and the expression shall be an integer constant expression. If the array is of unknown size, any nonnegative value is valid.

枚举标识符算作 constant-expression


这意味着你可以做类似这个愚蠢的例子的事情:

#include <stdio.h>

int main(void)
{
    int array[] = {
       [2] = 0,    // Initialize array[2] to 0
       [0] = 2,    // Initialize array[0] to 2
       [1] = 1     // Initialize array[1] to 1
    };

    for (size_t i = 0; i < (sizeof array / sizeof array[0]); ++i)
        printf("array[%d] = %d\n", i, array[i]);

    return 0;
}

上面的程序应该打印

array[0] = 2
array[1] = 1
array[2] = 0