Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ellipsis in array initialization in C kernel module

Tags:

c

kernel

I was examining some code on github https://github.com/umlaeute/v4l2loopback/blob/master/v4l2loopback.c and came across this line, which baffles me. Is this some incredibly cool kernel macro or gcc feature that I don't know about? What does the = -1 do?

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

The line in question is the first, the next two given for context (this is creating a cmdline-specifiable parameter using a kernel macro http://lxr.free-electrons.com/source/include/linux/moduleparam.h#L103 )

Anyway, what is going on with the array initialization? How does that syntax work?

like image 217
dmi_ Avatar asked Jan 24 '13 23:01

dmi_


1 Answers

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.

like image 142
Carl Norum Avatar answered Oct 24 '22 08:10

Carl Norum