AllowShortBlocksOnASingleLine未按预期工作,求排查配置问题
问题描述
我在用clang-format格式化C源文件,希望单行代码块比如:
if(condition) { do_something(); }
能保持原样。我开启了AllowShortBlocksOnASingleLine选项,本以为能满足需求,但实际它把原本的单行块比如:
if(new_node == NULL) { return; }
拆成了多行:
if(new_node == NULL) { return; }
其他类似代码块也出现同样情况,完全不符合预期。以下是我的代码示例和.clang-format配置文件,请问哪里配置错了?
代码示例
static Node * create_node(MAT_VERTEX v) { Node *new_node = malloc(sizeof(Node)); if(new_node == NULL) { return; } while(1) { return; } new_node->data = v; new_node->next = NULL; return new_node; enum FOOD breakfast = cereal; switch(breakfast) { case eggs: { int x = 3; int y; for(y = 5; y < x; y--) { } break; } case bacon: { int x = 4; if(x != 0) { int y = -5; } break; } case ham: { int decision = 1; int traffic = 1; if(decision) { traffic = 0; do_nothing_function(); } else { traffic = 3; another_do_nothing_function(); } break; } default: { break; } } }
.clang-format配置文件
Language: Cpp BreakBeforeBraces: Custom BraceWrapping: AfterCaseLabel: false AfterClass: false AfterControlStatement: Never AfterFunction: true AfterNamespace: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: true BeforeElse: true BeforeWhile: false IndentBraces: false SplitEmptyFunction: true AllowShortBlocksOnASingleLine: Always # AllowShortIfStatementsOnASingleLine: Never AllowShortFunctionsOnASingleLine: None IndentCaseBlocks: false IndentCaseLabels: true IndentWidth: 4 PointerAlignment: Right QualifierAlignment: Leave SeparateDefinitionBlocks: Leave AlignAfterOpenBracket: Align BinPackParameters: false BinPackArguments: false AlwaysBreakAfterReturnType: TopLevelDefinitions MaxEmptyLinesToKeep: 5 IncludeBlocks: Preserve SortIncludes: Never SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: false SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true SpaceBeforeCaseColon: false SpaceBeforeParens: Never SpaceBeforeRangeBasedForLoopColon: true SpaceBeforeSquareBrackets: false SpaceInEmptyBlock: true SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 3 SpacesInContainerLiterals: false SpacesInSquareBrackets: false
问题原因及解决办法
问题出在BraceWrapping下的AfterControlStatement配置。你设置的Never会强制控制语句(if/while等)后的大括号必须换行,这直接覆盖了AllowShortBlocksOnASingleLine的生效逻辑。
需要把AfterControlStatement从Never改成MultiLine,这样clang-format会对单行短代码块保持原样,仅对包含多行内容的代码块换行处理。
修改后的BraceWrapping部分配置如下:
BraceWrapping: AfterCaseLabel: false AfterClass: false AfterControlStatement: MultiLine # 修改此处 AfterFunction: true AfterNamespace: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: true BeforeElse: true BeforeWhile: false IndentBraces: false SplitEmptyFunction: true
如果还希望if语句的条件判断和整个代码块完全在一行(比如if(cond){do();}),可以取消注释AllowShortIfStatementsOnASingleLine并设置为Always,这一步可根据你的实际格式需求选择。
内容的提问来源于stack exchange,提问作者Mode77
相关产品推荐
相关产品推荐

