在C中,[foo] = bar是什么意思?

时间:2021-07-09 16:55:19

I was just reading some code in the st terminal emulator and came across this syntax:

我只是在st终端模拟器中读取一些代码并遇到了这种语法:

static void (*handler[LASTEvent])(XEvent *) = {
    [KeyPress] = kpress,
    [ClientMessage] = cmessage,
    /* Removed some lines for brevity ... */
};

I have never seen this syntax in C and I am not even sure what to google for. I have a rough idea what it does (defining handler as an array of function pointers), but I would like to understand this syntax better. It seems to be valid at least in C99, but I am looking for some more details why this is correct, how exactly it works and maybe a pointer to the C standard where this syntax is defined.

我从未在C中看到过这种语法,我甚至不确定谷歌的用途。我粗略地了解它的作用(将处理程序定义为函数指针数组),但我想更好地理解这种语法。它似乎至少在C99中是有效的,但我正在寻找更多细节,为什么这是正确的,它是如何工作的,也许是指向定义这种语法的C标准的指针。

1 个解决方案

#1


13  

This is initializing an array of function pointers with enum indexes. See here.

这是使用枚举索引初始化一个函数指针数组。看这里。

As mentioned in the comments below uses Designated Initializers.

如下面的评论中所述,使用指定的初始化程序。

This short example should show how it can be used.

这个简短的例子应该说明如何使用它。

enum indexes {ZERO, ONE, TWO, FOUR=4};
int array[5] = {[FOUR]=1, [TWO]=9};

for(int i = 0; i < 5; i++)
    printf("%d, ", array[i]);

This prints out

打印出来

0, 0, 9, 0, 1,

#1


13  

This is initializing an array of function pointers with enum indexes. See here.

这是使用枚举索引初始化一个函数指针数组。看这里。

As mentioned in the comments below uses Designated Initializers.

如下面的评论中所述,使用指定的初始化程序。

This short example should show how it can be used.

这个简短的例子应该说明如何使用它。

enum indexes {ZERO, ONE, TWO, FOUR=4};
int array[5] = {[FOUR]=1, [TWO]=9};

for(int i = 0; i < 5; i++)
    printf("%d, ", array[i]);

This prints out

打印出来

0, 0, 9, 0, 1,