简体   繁体   English

我可以在 C++ 中扩展条件表达式吗

[英]Can I extend conditional expression in C++

Can I make conditional expression with more than one else if:如果出现以下情况,我是否可以使用多个 else 进行条件表达式:

Casual condition:休闲条件:

int number = 50;
if (number > 23) cout << "The variable number is greater then 23 " << endl;
else cout << "23 is greater then variable number"  << endl;

Conditional expression:条件表达式:

 int number = 50;
 cout << (number > 23 ? "The variable number is greater then 23 " : "23 is greater then variable number")<< endl;
 

Is it possible to add more "else if" in this second case or it's only possible to add one condition consisting from "if and else"是否可以在第二种情况下添加更多“else if”,或者只能添加一个由“if and else”组成的条件

Similar to an else if , you could just have the else case be another conditional:else if类似,您可以将 else 情况设为另一个条件:

condition1 ? val1 :
condition2 ? val2 :
condition3 ? val3 :
val4

which is kind of equivalent to这有点相当于

if (condition1)
    val1
else if (condition2)
    val2
else if (condition3)
    val3
else
    val4

No there's no way to have an else-if in an inline conditional ('?:' syntax).不,无法在内联条件('?:' 语法)中使用 else-if。 You could maybe approach this with nested '?:s' with parentheses , but it'd be ugly.您可以使用带括号的嵌套 '?:s' 来解决这个问题,但这会很丑陋。

Edit: looking at the other answer, i guess you can and it's not that ugly!编辑:看另一个答案,我想你可以,而且没那么难看! But I haven't seen this pattern in practice.但是我在实践中没有看到这种模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM