21

我正在检查 github https://github.com/umlaeute/v4l2loopback/blob/master/v4l2loopback.c上的一些代码,遇到了这条线,这让我感到困惑。这是我不知道的一些非常酷的内核宏或 gcc 功能吗?做什么的= -1

static int video_nr[MAX_DEVICES] = { [0 ... (MAX_DEVICES-1)] = -1 };
module_param_array(video_nr, int, NULL, 0444);
MODULE_PARM_DESC(video_nr, "video device numbers (-1=auto, 0=/dev/video0, etc.)");

有问题的行是第一行,接下来的两行是针对上下文给出的(这是使用内核宏http://lxr.free-electrons.com/source/include/linux/moduleparam.h#L103创建一个 cmdline-specifiable 参数)

无论如何,数组初始化发生了什么?该语法如何工作?

4

1 回答 1

24

You've found an example of designated initializers. C99 & C11 don't go quite as far as your example, but they have some pretty flexible support for this kind of behaviour. Your specific example (using the ...) is a GCC extension. From the link:

To initialize a range of elements to the same value, write [first ... last] = value. This is a GNU extension. For example,

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

So that means your example is creating an array of size MAX_DEVICES and initializing every element in that array to -1.

For reference, the only standard-supported behaviour is to assign specific indices, rather than ranges:

[constant-expression] = initializer-value

There is a more complicated example in my copy of the spec:

int a[MAX] = {
            1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0
};

Which initializes the first five and last five elements of the array to explicit values. The middle values (if any) would be 0.

于 2013-01-24T23:59:46.840 回答