如何配置Clang-Format使if-else if-else代码块单行显示?
问题:配置Clang-Format 14实现if/else if/else与代码块单行显示
期望保留的代码格式
if (type.empty()) { os << "!EMPTY"; } else if (type->as_qubit()) { os << types::qubit_type_name; } else { os << *type; }
Clang-Format当前格式化结果
if (type.empty()) { os << "!EMPTY"; } else if (type->as_qubit()) { os << types::qubit_type_name; } else { os << *type; }
当前.clang-format配置
--- BasedOnStyle: Google Language: Cpp AlignAfterOpenBracket: DontAlign AlignTrailingComments: true AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortEnumsOnASingleLine: true AllowShortBlocksOnASingleLine: Always AllowShortCaseLabelsOnASingleLine: true AllowShortIfStatementsOnASingleLine: AllIfsAndElse AllowShortFunctionsOnASingleLine: All AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: true BreakBeforeBraces: Attach BreakConstructorInitializers: BeforeComma ColumnLimit: 120 ConstructorInitializerIndentWidth: 0 Cpp11BracedListStyle: false DerivePointerAlignment: false IndentWidth: 4 PointerAlignment: Right ReflowComments: false ---
解决方案
可以通过调整配置实现目标效果,核心是确保关键选项设置,并补充括号包裹规则:
保留现有配置中已正确设置的两个选项:
AllowShortIfStatementsOnASingleLine: AllIfsAndElse:允许if、else if、else语句与代码块在同一行AllowShortBlocksOnASingleLine: Always:允许所有短代码块与括号在同一行
调整
BreakBeforeBraces为Custom,并添加BraceWrapping配置,确保if/else的括号不强制换行,同时保留Google风格对其他结构的处理:
修改后的完整配置如下:
--- BasedOnStyle: Google Language: Cpp AlignAfterOpenBracket: DontAlign AlignTrailingComments: true AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortEnumsOnASingleLine: true AllowShortBlocksOnASingleLine: Always AllowShortCaseLabelsOnASingleLine: true AllowShortIfStatementsOnASingleLine: AllIfsAndElse AllowShortFunctionsOnASingleLine: All AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: true BreakBeforeBraces: Custom BraceWrapping: AfterIf: false AfterElse: false AfterFunction: Attach AfterClass: Attach AfterNamespace: Attach AfterEnum: Attach AfterStruct: Attach AfterUnion: Attach AfterExternBlock: Attach BeforeCatch: true BeforeElse: true IndentBraces: false BreakConstructorInitializers: BeforeComma ColumnLimit: 120 ConstructorInitializerIndentWidth: 0 Cpp11BracedListStyle: false DerivePointerAlignment: false IndentWidth: 4 PointerAlignment: Right ReflowComments: false ---
这样配置后,只要代码块内容长度不超过ColumnLimit(你设置的120),Clang-Format 14就会将if、else if、else与其对应的代码块保持在同一行,同时其他结构(如函数、类)仍遵循Google风格的括号附着规则。
内容的提问来源于stack exchange,提问作者rturrado
相关产品推荐
相关产品推荐

