elseif shorthand

Hello,

I know there is a shorthand for if and else conditions, it is as follows

 
 A = (B<C)? B:C;


What about elseif? the condition appears to only cater for if and else condition. Is there a shorthand version that includes elseif? and how is it written?

Thanks.

David.
I'd like to note that the conditional operator is not really a shorthand for an if statement, as an if statement contains statements, while the conditional operator is an expression that contains sub-expressions. So while there are cases that you may be able construct equivalent code using either, it is not a certain thing.

To answer your question, there is no special shorthand for having multiple conditions in a conditional operator expression. You will just have to nest them yourself:
A = x ? 3 : (y ? 2 : 1);
is equivalent to
1
2
3
4
5
6
7
if(x) {
    A = 3;
} else if(y) {
    A = 2;
} else {
    A = 1;
}
The operator is right-associative, which means you can leave the parentheses out.
1
2
a = x? 3:
    y? 2: 1;

Note that the ternary if operator is not a statement. This means that mismatches between type and value category can occur, so it cannot be used to replace if and else-if in all cases.
Last edited on
Thanks a lot. @Zhuge and @mbozzi
Now I know better.
David.
Topic archived. No new replies allowed.