如何配置Clang Format使链式else if语句单行显示?
Configuring .clang-format for Compact If/Else Chains
Got it, let's nail down the .clang-format settings to get that compact, single-line if/else chain you're after. Here's the key configuration you'll need, plus a breakdown of what each setting does:
Required Settings
Add these lines to your .clang-format file:
# Allow if/else if/else blocks to all fit on single lines AllowShortIfStatementsOnASingleLine: AllIfsAndElse # Allow single-line code blocks to stay on the same line as their braces AllowShortBlocksOnASingleLine: Always
What Each Setting Does
AllowShortIfStatementsOnASingleLine: AllIfsAndElse: This tells clang-format to extend single-line formatting to the entireif/else ifchain (and any finalelseclause) instead of just standaloneifstatements. Without this, it might splitelse ifsections onto separate lines.AllowShortBlocksOnASingleLine: Always: This ensures the code inside your braces (likeindex = 1;) stays on the same line as the opening and closing braces, rather than being split onto a new line.
Resulting Format
When you run clang-format on your code, it will output exactly the style you want:
if (value.Is<bool>()) { index = 1; } else if (value.Is<int>()) { index = 2; } else if (value.Is<unsigned int>()) { index = 3; } else if (value.Is<long long>()) { index = 4; } else if (value.Is<unsigned long long>()) { index = 5; } else if (value.Is<float>()) { index = 6; } else if (value.Is<double>()) { index = 7; } else if (value.Is<long double>()) { index = 8; }
If you later add an else clause, it will follow the same compact style too:
// Example with an else clause if (value.Is<bool>()) { index = 1; } else if (value.Is<int>()) { index = 2; } else { index = 0; }
内容的提问来源于stack exchange,提问作者Walrus
相关产品推荐
相关产品推荐

