Reputation: 191
Is there a way to do this
bool retA = true, retB=false retC=true,retD=false;
return ( (if RetA -> A) + (if RetB -> B) + (if RetC -> C) + (if RetD -> A) )
Basically if {A,B,C,D] = {1,2,3,4}, return value is 1+0+3+0 = 4. You can do this with 16 different if/else statements, but the code is not pretty.
Upvotes: 2
Views: 155
Reputation: 1074335
I think you're looking for the conditional operator, which looks like this:
testExpression ? trueExpression : falseExpression
.
So:
return (retA ? A : 0) + (retB ? B : 0) + (retC ? C : 0) + (retD ? D : 0);
All of the languages syntactically derived from B have the conditional operator (C, C++, Java, JavaScript, and several others).
Side note: You were using A
after the RetD
condition, but I figure you meant D
. Also, no need for the outer pair of ()
, so I left them off.
You'll sometimes hear the conditional operator called "the ternary operator," which is fine but isn't quite correct: It's a ternary operator (that is, an operator that accepts three operands) just like *
is a binary operator (an operator that accepts two operands). As far as I know, the conditional is C++'s only ternary operator, but in theory someday there could be more...
Upvotes: 8