RObertos12
RObertos12

Reputation: 87

Can I extend conditional expression in C++

Can I make conditional expression with more than one else if:

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"

Upvotes: 1

Views: 133

Answers (2)

Anita W
Anita W

Reputation: 101

No there's no way to have an else-if in an inline conditional ('?:' syntax). You could maybe approach this with nested '?:s' with parentheses, but it'd be ugly.

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.

Upvotes: 1

IlCapitano
IlCapitano

Reputation: 2084

Similar to an else if, you could just have the else case be another conditional:

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

Upvotes: 1

Related Questions