Placement of const with clang-format

3.8k Views Asked by At

clang-format has tons of configuration options regarding whitespace and also some about code order (order of includes). Is it possible to reorder const-qualifiers so that they are placed to the right of the respective type?

Example: The declaration const int x = 0; should be formatted to int const x = 0;.

3

There are 3 best solutions below

3
On BEST ANSWER

From version 14.0 onwards, clang-format offers the option QualifierAlignment which can take the following values: Leave, Left, Right and Custom.

OP's request can thus be achieved with

clang-format -style="{QualifierAlignment: Right}" <file-name>

Documentation can be found here

Edit: More information on values of QualifierAlignment

  • Leave: clang-format will not touch qualifier placement
  • Left: clang-format will align qualifiers left
  • Right: clang-format will align qualifiers right
  • Custom:

When Custom is used as the value for QualifierAlignment, the order from the clang-format option QualifierOrder is used. These two options have to then be used together, like so:

clang-format -style="{QualifierOrder: ['inline', 'static', 'type', 'const'], QualifierAlignment: Custom}" <file-name>

Edit2: It seems the prefix 'QAS' of QAS_Right, QAS_Left etc is not needed.

0
On

This feature seems to be now in the works: https://reviews.llvm.org/D69764

0
On

EDIT: After clang-format version 14

As of clang-format version 14, the option for QualifierAlignment with value Right can be used. (See https://clang.llvm.org/docs/ClangFormatStyleOptions.html for alternative values)

Set the following in the configuration file:

QualifierAlignment: Right

Warning:

Setting QualifierAlignment to something other than Leave, COULD lead to incorrect code formatting due to incorrect decisions made due to clang-formats lack of complete semantic information. As such extra care should be taken to review code changes made by the use of this option.

Before clang-format version 14

Unfortunately, such feature is not available according to the documentation.