我们如何使用三元运算符和尽可能多的 else-if?

How can we use ternary operator with as many else-if as we want?

基本的三元运算符用法是

(condition) ? True part : False part

我们如何向其中添加 "multiple-else-if" 功能?

(condition 1)? True statements for cond. 1 :(condition 2)?  True statements for cond. 2: else statements

我们可以使用条件运算符在一行中添加 else if 条件。

例子

#include <stdio.h>
int main(){
     for(int i = 1; i<=10; i++)
          printf("%d%s\n",i,(i==1)?"st":(i==2)?"nd":(i==3)?"rd":"th");
}

结果

1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th

链接三元运算符时,格式化是使其可读的关键:

试图在一条长线上完成所有操作会让人难以理解。

int result = (oper=='+')?  a+b : 
             (oper=='-')?  a-b : 
             (oper=='/')?  a/b : 
             (oper=='*')?  a*b : 
             (oper=='^')?  a^b : 
             (oper=='&')?  a&b : 
             0;

或者,格式化 Zafeer 的示例:

#include <stdio.h>
int main(){
     for(int i = 1; i<=10; i++)
          printf("%d%s\n",i, (i==1)? "st":
                             (i==2)? "nd":
                             (i==3)? "rd": 
                                     "th");
}

语法非常清楚地说明了如何做到这一点。语法是:

conditional_expression
    : logical_or_expression
    | logical_or_expression '?' expression ':' conditional_expression
    ;

https://www.lysator.liu.se/c/ANSI-C-grammar-y.html

也就是说 : 之后的内容应该是有效的 conditional_expression.

但这很少是一件好事。根据你给出的答案,你想用它来格式化打印输出。但是把它提取到一个单独的函数中会好得多,像这样:

const char* suffix(int n)
{
    static const char suffix[][3] = { "st", "nd", "rd", "th" };
    int rIndex;
    /* Some logic */
    return suffix[rIndex];
}

然后

printf("%d%s\n", i, suffix(i));

就流量控制而言,三元组的工作方式与if-else相同,嵌套方式与if-else

相同

简单

if (cond ) yes ; else no;
~
(cond) ? yes : else no

阶梯

if (cond ) yes ;
else if (cond2) cond2yes;
else  if (cond3) cond3yes;
else cond3no;
~
cond  ? yes :
cond2 ? cond2yes :
cond3 ? cond3yes :
cond3no

最近我需要一堆复杂的嵌套三元组,我发现 像这样构造它们是最容易阅读的,尤其是 在括号匹配编辑器的帮助下:

cond ? (
    yes
) : ( cond2 ? (
        cond2yes
    ) : ( cond3 ? (
            cond3yes
        ) : (
            cond3no
        )
    )
)