如何使用clang-format控制三元运算符的缩进

How to control indent of ternary operator using clang-format?

本文关键字:三元 运算符 缩进 何使用 clang-format 控制      更新时间:2023-10-16

如何控制clang-format中三元运算符的缩进?我想要有普通延拓独立,例如

int foobar = bar ? a
        : b;

我得到了运算符

的对齐
int foobar = bar ? a
                 : b;

我已经有AlignOperands: false什么好主意吗?

(完整选项:style='{BasedOnStyle: LLVM, TabWidth: 4, IndentWidth: 4, ContinuationIndentWidth: 8, UseTab: Always, alignafteropen括号:false, BreakBeforeBinaryOperators: All, AlwaysBreakTemplateDeclarations: true, AlignOperands: false, ColumnLimit: 120}')

我相信如果合并https://reviews.llvm.org/D50078会解决这个问题。

如果你想更花哨,我可以推荐这段代码。

int a = 10;
int b = 20;
bool flag = true;
int c =  
     flag ? 
         a 
        : b;
std::cout << c << "n";

或者你可以这样做,你的选择:

当多个三元操作符链接时,例如if/else-if/else if/……/else序列,clang-format将继续对齐冒号使用问号,这增加了每个的缩进条件:

int a = condition1 ? result1
                   : condition2 ? result2
                                : condition3 ? result3
                                             : result4;

此补丁检测情况(例如,在false分支中使用条件)在这种情况下,为了避免缩进:

int a = condition1 ? result1
      : condition2 ? result2
      : condition3 ? result3
                   : result4;

当BreakBeforeTernaryOperators为false时,其格式如下:

int a = condition1 ? result1 :
        condition2 ? result2 :
        conditino3 ? result3 :
                     result4;