17

In our project, we sometimes initialise arrays on one line, and sometimes we initialise them as blocks. That is

strings::UniChar const s[] = {'H', 'e', 'l', 'l', 'o'};

vs

strings::UniChar const s[] = 
{
 'H', 
 'e', 
 'l', 
 'l', 
 'o'
};

I would like to clang-format to be able to distinguish between the two types and not convert the second into the first one or align the elements after the opening brace. That is not like this:

strings::UniChar const s[] = {'H', 
 'e', 
 'l', 
 'l', 
 'o'};

Is there a way to achieve that using config files?

asked Jun 27, 2016 at 16:09
2
  • 1
    Why don't you disable clang format just for those declarations with a /* clang-format off */ Commented Jun 27, 2016 at 16:40
  • 2
    It is one of the options I consider, I hoped there was an automated way to do that. Commented Jun 27, 2016 at 16:53

4 Answers 4

29

Adding a comma after the last array element causes clang-format (tried with v6.0.0) to align the elements to the left side, like your second example.

// With a trailing comma.
char buf[] = {
 'a',
 'b',
};
// Without a trailing comma.
char buf2[] = {'a', 'b'};
kevr
4554 silver badges9 bronze badges
answered Feb 8, 2018 at 19:13
Sign up to request clarification or add additional context in comments.

Comments

10

try "Cpp11BracedListStyle: false"

answered Aug 2, 2017 at 14:49

Comments

5

You can force a line break with //:

strings::UniChar const s[] = {
 'H', //
 'e', //
 'l', //
 'l', //
 'o' //
};
answered Sep 24, 2022 at 13:07

2 Comments

Thank you for this idea. Works great. I had to do this in conjunction with the comma after the last element and setting Cpp11BracedListStyle: false to get the format I wanted for the initializer on a multi-dimensional array.
Hacky workaround but it works. But you should't have to fight your formatter to get things to look the way you want.
1

This is an absolutely relevant question, since there's still no way to disable bin packing for array initializers.

The most flexible option is to use comments, as it lets you format arrays into anything, including visually distinct matrices, e.g.:

static constexpr bool shape[] = {
 0, 1, 0, //
 1, 1, 1, //
 0, 1, 1, //
};

Without comments, clang-format will put that array in one line and break on column limit, and there's no way to prevent it by changing the config file.

If you don't care for that and only want 1 column initializations, then the already mentioned Cpp11BracedListStyle: false is enough.

answered Oct 1, 2024 at 9:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.