Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clang-format, array initialisers

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?

like image 503
Ibolit Avatar asked Jun 27 '16 16:06

Ibolit


People also ask

Is clang format good?

clang-format is a tool to automatically format C/C++/Objective-C code, so that developers don't need to worry about style issues during code reviews. It is highly recommended to format your changed C++ code before opening pull requests, which will save you and the reviewers' time.

Can clang format break code?

Short answer: YES. The clang-format tool has a -sort-includes option. Changing the order of #include directives can definitely change the behavior of existing code, and may break existing code.

Where do I put the clang format?

clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

How do I turn off clang format?

Disabling Formatting on a Piece of Code The code between a comment // clang-format off or /* clang-format off */ up to a comment // clang-format on or /* clang-format on */ will not be formatted. The comments themselves will be formatted (aligned) normally.


1 Answers

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'};
like image 124
emlai Avatar answered Nov 10 '22 06:11

emlai