cstructinitializerclang-format

Clang-format: how to format C struct initializer this way


I'm using the linux kernel .clang-format as a reference, but this part is bothering me.

How can I get clang-format to format this code

const struct my_struct hello = {.id = 0,
                                .modsmin = 10,
                                .modsmax = 20,
                                .strengthmin = 0,
                                .strengthmax = 100,
                                .color = COLOR_FOREGROUND };

to this

const struct my_struct hello = {
    .id = 0,
    .modsmin = 10,
    .modsmax = 20,
    .strengthmin = 0,
    .strengthmax = 100,
    .color = COLOR_FOREGROUND
};

Solution

  • Looking at the documentation, there don't seem to be any clang-format style options which will do what you want.

    But, you can use the "comma-after-last-item" trick. Put a comma after the last designated initializer, before the final closing brace. I believe this is still valid C code. Then clang-format will put each initializer on a separate line, and this will move the indentation back to what you're looking for. So the output would look like this:

    const struct my_struct hello = {
        .id = 0,
        .modsmin = 10,
        .modsmax = 20,
        .strengthmin = 0,
        .strengthmax = 100,
        .color = COLOR_FOREGROUND,
    };
    

    This behavior is not documented anywhere (as far as I know), so I suppose it could be changed in the future. But this behavior has been there for many years and many versions of clang-format so I think it is reasonable to rely on it.