Placement of const with clang-format

Viewed 1933

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 Answers

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.

Related