it's also called the conditional operator
Printable View
it's also called the conditional operator
Depending on the situation, if I need readability, or if the test is lengthy, I usually do something like:Quote:
Originally posted by pianorain
They're not so bad if you add a few parenthesis for readability.
return st1 ? sv1 : (st2 ? sv2 : (st3 ? sv3 : sv4));
It makes it farily simple to understand, and its shorter than a big if/else ladder.Code:return Condition1 ? ReturnValue1 :
Condition2 ? ReturnValue2 :
Condition3 ? ReturnValue3 :
Condition4 ? ReturnValue4 : Returnvalue5;
Quzah.
I disagree.
Code readability is very important and these codes are equivalent:
Code:return Condition1 ? ReturnValue1 :
Condition2 ? ReturnValue2 :
Condition3 ? ReturnValue3 :
Condition4 ? ReturnValue4 : Returnvalue5;
The purpose of the code using "if" is (more) obvious, even to a programmer not familiar with C/C++/Java/Omicron. It is easier to read and should therefore be used.Code:if (Condition1) return ReturnValue1;
if (Condition2) return ReturnValue2;
if (Condition3) return ReturnValue3;
if (Condition4) return ReturnValue4;
return ReturnValue5;
Anyways, I haven't encountered many real-life situations where such return conditions are used.
The only time I've done something like that was when I was confusing my second-rate C++ professor. Not saying it's bad...it just has very specialized uses. ;)Quote:
Originally posted by quzahCode:return Condition1 ? ReturnValue1 :
Condition2 ? ReturnValue2 :
Condition3 ? ReturnValue3 :
Condition4 ? ReturnValue4 : Returnvalue5;
>I've heard from a couple of people that using the operators "?:" instead of using "if/else" is bad coding practice and should
>be avoided unless it makes the code MUCH clearer.
It's funny how questions like these seem to crop up so much and turn into large debates. The conditional operator is a Bad Thing like goto is a Bad Thing, it isn't. It's just another tool that if used without discipline can create impenetrable code. Sometimes there's a better solution, sometimes not, but that's a decision up to the individual programmer.
-Prelude