Let's say I have a criteria and I want to add a delta if that criteria is true, and do the opposite (subtract) if it is false.
bool bBoolean;
int iDelta;
int iQuantity;
Is there a more concise and elegant way to write that piece of code ? I mean without repeating the keywords iQuantity and iDelta.
if(bBoolean)
iQuantity -= iDelta;
else
iQuantity += iDelta;
The shortest thing I can think of is:
iQuantity += (bBoolean) ? -iDelta : iDelta;
Edit: This is commonly called a ternary statement, though it's proper name (what it's called in the standard) is "conditional expression" or "conditional operator".
(Thanks to Rune for the official name.)
This is the ternary operator. It is frowned upon by some for its potential to be less clear than if...else. I like it, but try to be careful.
int sign = criteria ? -1 : 1;
quantity += (delta * sign);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With