Lucien Brule Lucien Brule - 1 year ago 61
Linux Question

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

I was browsing the Linux source and I came across an unfamiliar piece of code on line 400 of initramfs. I get that the names in the brackets are states from an enum on 188. It also seems to me that this is a default array setting function pointers ( I could be wrong).

I don't understand what the brackets are for, what's an example use case?I also found the equal signs confusing. Additionally, I'd like to know if there's a general name for the pattern the code implements.

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,

Side; Apologies for a naive/general question, I'm trying to broaden my knowledge of C. I searched for and couldn't find a comprehensive commented version of the source in english.

Answer Source

That is a GCC extension for designated initialization.

It's a combination or mixture of standard designated structure/union initialization and array initialization.

To clarify, in the C standard the syntax using square brackets [] is for array initialization, while structure/union initialization uses a dot-syntax. GCC invented their own syntax for structure/union initialization, basing it on the (then proposed) standard array-initialization syntax. This dependency on the GCC C compiler is what makes the Linux kernel hard to port to other compilers. Fortunately (or maybe not) many compilers try to make themselves compatible with GCC, including extensions like that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download