如何通过clang-format配置仅缩进case标签后的大括号(保持case标签不缩进)
How to Configure clang-format for Case Labels with Indented Braces (No Label Indent)
Great question! This exact formatting style is absolutely achievable with clang-format—you just need to combine a few specific settings instead of relying solely on IndentCaseLabels. Here's how to set it up:
Required Configuration
Add these settings to your .clang-format file (adjust IndentWidth to match your preferred indent size):
--- Language: Cpp IndentWidth: 4 IndentCaseLabels: false BreakBeforeBraces: Custom BraceWrapping: AfterCaseLabel: true IndentCaseBlocks: true
What Each Setting Does
IndentCaseLabels: false: Ensurescaselabels stay aligned with theswitchstatement (no extra indentation on the label itself).BraceWrapping: AfterCaseLabel: true: Forces the opening brace after acaselabel to start on a new line, instead of being inline withcase X:.IndentCaseBlocks: true: Indents the brace block under thecaselabel by one level, while keeping subsequent statements likebreakaligned with thecaselabel.IndentWidth: 4: Sets the number of spaces for each indent (adjust to 2 if you prefer smaller indents).
Resulting Formatted Code
With these settings, your code will be formatted exactly as you requested:
switch(a) { case 1: { do_some_thing(); } break; }
Why Your Initial Attempts Didn't Work
- Setting
IndentCaseLabels: trueindents both thecaselabel and all its content, which isn't what you wanted. - Setting
IndentCaseLabels: falsekeeps the label unindented but also leaves the brace at the same level as the label—missing the indentation on the brace block that you needed. The combination ofBraceWrappingandIndentCaseBlocksfixes this gap.
内容的提问来源于stack exchange,提问作者ZegWe
相关产品推荐
相关产品推荐

