it's also called the conditional operator
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: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.
Hope is the first step on the road to disappointment.
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.
Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling
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.Originally posted by quzahCode:return Condition1 ? ReturnValue1 : Condition2 ? ReturnValue2 : Condition3 ? ReturnValue3 : Condition4 ? ReturnValue4 : Returnvalue5;
If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein
>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
My best code is written with the delete key.